Question

You are given a sequence of integer values. Describe an algorithm requiring no worse than O(n2)...

You are given a sequence of integer values. Describe an algorithm requiring no worse than O(n2) time for finding the length of a longest rising subsequence in that array. A subsequence is rising when each element is less than or equal to the one following it. For example, in the sequence [23, -15, 10, 25, 7, 32], the length of a longest rising sequence is 4, found in the subsequence [-15, 10, 25, 32].

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Length of Longest Increasing Subsequence
Algorithm written using Python conventions and descriptive identifiers.

The O(n^2) Dynamic Programming Solution
def dynamic_programming_solution(sequence):

longest_subsequence_ending_with = []
backreference_for_subsequence_ending_with = []
current_best_end = 0

for curr_elem in range(len(sequence)):
# It's always possible to have a subsequence of length 1.   
longest_subsequence_ending_with.append(1)

# If a subsequence is length 1, it doesn't have a backreference.
backreference_for_subsequence_ending_with.append(None)

for prev_elem in range(curr_elem):
subsequence_length_through_prev = (longest_subsequence_ending_with[prev_elem] + 1)

# If the prev_elem is smaller than the current elem (so it's increasing)
# And if the longest subsequence from prev_elem would yield a better
# subsequence for curr_elem.
if ((sequence[prev_elem] < sequence[curr_elem]) and
(subsequence_length_through_prev >
longest_subsequence_ending_with[curr_elem])):

# Set the candidate best subsequence at curr_elem to go through prev.   
longest_subsequence_ending_with[curr_elem] = (subsequence_length_through_prev)
backreference_for_subsequence_ending_with[curr_elem] = prev_elem
# If the new end is the best, update the best.   

if (longest_subsequence_ending_with[curr_elem] >
longest_subsequence_ending_with[current_best_end]):
current_best_end = curr_elem
# Output the overall best by following the backreferences.  
best_subsequence = []
current_backreference = current_best_end

while current_backreference is not None:
best_subsequence.append(sequence[current_backreference])
current_backreference = (backreference_for_subsequence_ending_with[current_backreference])

best_subsequence.reverse()

return len(best_subsequence)   


The O(n log n) Dynamic Programming Solution
def find_smallest_elem_as_big_as(sequence, subsequence, elem):
"""Returns the index of the smallest element in subsequence as big as   
sequence[elem]. sequence[elem] must not be larger than every element in
subsequence. The elements in subsequence are indices in sequence. Uses
binary search."""

low = 0
high = len(subsequence) - 1

while high > low:
mid = (high + low) / 2
# If the current element is not as big as elem, throw out the low half of   
# sequence.   
if sequence[subsequence[mid]] < sequence[elem]:
low = mid + 1
# If the current element is as big as elem, throw out everything bigger, but
# keep the current element.   
else:
high = mid

return high


def optimized_dynamic_programming_solution(sequence):
# Both of these lists hold the indices of elements in sequence and not the   
# elements themselves.
# This list will always be sorted.
smallest_end_to_subsequence_of_length = []

# This array goes along with sequence (not
# smallest_end_to_subsequence_of_length). Following the corresponding element
# in this array repeatedly will generate the desired subsequence.   
parent = [None for _ in sequence]

for elem in range(len(sequence)):
# We're iterating through sequence in order, so if elem is bigger than the
# end of longest current subsequence, we have a new longest increasing   
# subsequence.
if (len(smallest_end_to_subsequence_of_length) == 0 or
sequence[elem] > sequence[smallest_end_to_subsequence_of_length[-1]]):
# If we are adding the first element, it has no parent. Otherwise, we   
# need to update the parent to be the previous biggest element.   
if len(smallest_end_to_subsequence_of_length) > 0:
parent[elem] = smallest_end_to_subsequence_of_length[-1]
smallest_end_to_subsequence_of_length.append(elem)
else:
# If we can't make a longer subsequence, we might be able to make a   
# subsequence of equal size to one of our earlier subsequences with a
# smaller ending number (which makes it easier to find a later number that
# is increasing).   
# Thus, we look for the smallest element in   
# smallest_end_to_subsequence_of_length that is at least as big as elem
# and replace it with elem.   
# This preserves correctness because if there is a subsequence of length n
# that ends with a number smaller than elem, we could add elem on to the
# end of that subsequence to get a subsequence of length n+1.   
location_to_replace = find_smallest_elem_as_big_as(sequence, smallest_end_to_subsequence_of_length, elem)
smallest_end_to_subsequence_of_length[location_to_replace] = elem
# If we're replacing the first element, we don't need to update its parent
# because a subsequence of length 1 has no parent. Otherwise, its parent  
# is the subsequence one shorter, which we just added onto.   
if location_to_replace != 0:
parent[elem] = (smallest_end_to_subsequence_of_length[location_to_replace - 1])

# Generate the longest increasing subsequence by backtracking through parent.  
curr_parent = smallest_end_to_subsequence_of_length[-1]
longest_increasing_subsequence = []

while curr_parent is not None:
longest_increasing_subsequence.append(sequence[curr_parent])
curr_parent = parent[curr_parent]

longest_increasing_subsequence.reverse()

return len(longest_increasing_subsequence)

Add a comment
Know the answer?
Add Answer to:
You are given a sequence of integer values. Describe an algorithm requiring no worse than O(n2)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In this project, you will work on the algorithm (discussed in Module 1) to determine the...

    In this project, you will work on the algorithm (discussed in Module 1) to determine the length of the longest sub sequence of consecutive integers in an array You will implement the algorithm using Hash tables. You are provided with sample code (in C++ and Java) representing the linked list-based implementation of Hash tables (as an array of Linked Lists). You could go through the code to understand the implementation of a Hash table and the functions that can be...

  • 8. [10 points) Consider the following algorithm procedure Algorithm(: integer, n: positive integer; 81,...a s integers with vhilei<r print (l, r, mı, arn, 》 if z > am then 1:= m + 1 if za...

    8. [10 points) Consider the following algorithm procedure Algorithm(: integer, n: positive integer; 81,...a s integers with vhilei<r print (l, r, mı, arn, 》 if z > am then 1:= m + 1 if za then anstwer-1 return answer 18 and the (a) Assume that this algorithm receives as input the numbersz-32 and corresponding sequence of integers 2 | 3 1 1 4151617| 8| 9 | 10 İ 11 İ 12 | 13 | 14|15 | 16 | 17 |...

  • F a as a sequence of adjacent array elements such that each value in the run array was of size 10...

    f a as a sequence of adjacent array elements such that each value in the run array was of size 10 9. We define a "run" of elements o (except for the first) is one greater than the previous and looked like: value. For example, say the 3 2 16 9 7 8 9 2 a: position 0 3 We have three runs in this array: (1) between 9,10,1, 12) and, (3) between positions 7 and 8, (15, 16) positions...

  • I really would appreciate some help with this assignment and include comments please as I am...

    I really would appreciate some help with this assignment and include comments please as I am in this for learning. Part I: Maximum increasing subsequence (adapted from Programming Exercise 22.2) Write a program MaxlncreasingSubseq.java that prompts the user to enter a string and displays a maximum length increasing subsequence of characters. Here are four sample runs Enter a string: zebras ers Enter a string: Welcome Welo Enter a string: mmmoooooovwwvee mov Enter a string: abqrstcxyzdefghij abcdefghij You must use dynamic...

  • 5) (10 pts) Greedy Algorithms The 0-1 Knapsack problem is as follows: you are given a...

    5) (10 pts) Greedy Algorithms The 0-1 Knapsack problem is as follows: you are given a list of items, each item has an integer weight and integer value. The goal of the problem is to choose a subset of the items which have a sum of weights less than or equal to a given W with a maximal sum of values. For example, if we had the following five items (each in the form (weight, value)): 11(6, 13), 2(4, 10),...

  • Instructions You will be given an integer value less than 20. Based on the number given,...

    Instructions You will be given an integer value less than 20. Based on the number given, you will calculate the combination of ten and five dollar bills, toonies (2 dollar coins) and loonies (1 dollar coins) needed to pay such that you pay using as many of the largest bills/coins first. Details Input Input consists of an positive integer (named value) that is less than 20 (read in via input) Processing You will need declare and initialize the following integer...

  • C# 1. Given two lengths between 0 and 9, create an rowLength by colLength matrix with...

    C# 1. Given two lengths between 0 and 9, create an rowLength by colLength matrix with each element representing its column and row value, starting from 1. So the element at the first column and the first row will be 11. If either length is out of the range, simply return a null. For exmaple, if colLength = 5 and rowLength = 4, you will see: 11 12 13 14 15 21 22 23 24 25 31 32 33 34...

  • An m×n array A of real numbers is a Monge array if for all i,j,k, and l such that 1≤i<k≤m and ...

    An m×n array A of real numbers is a Monge array if for all i,j,k, and l such that 1≤i<k≤m and 1≤j<l≤n , we have >A[i,j]+a[k,l]≤A[i,l]+A[k,j]> In other words, whenever we pick two rows and two columns of a Monge array and consider the four elements at the intersections of the rows and columns, the sum of the upper-left and lower-right elements is less than or equal to the sum of the lower-left and upper-right elements. For example, the following...

  • A method called linearSearch(), which takes as parameters an array of int followed by three values...

    A method called linearSearch(), which takes as parameters an array of int followed by three values of type int, and returns a value of type int. The first int parameter represents a key, the second int parameter represents a starting position, and the third int parameter represents an end position. If the key occurs in the array between the start position (inclusive) and the end position (exclusive), the method returns the position of the first occurrence of the key in...

  • Please Help! Need in Java C++ Object oriented programming. Thank you! Method 2: public static int...

    Please Help! Need in Java C++ Object oriented programming. Thank you! Method 2: public static int sumCapped(int[] nums, int x) This method will return the largest sum that is less than or equal x found in one pass of the array. This means that you must check each number in succession to determine whether or not you should add it in. For example, for the array {4, 2, 3, 5} with the value of the paramter x set to 7,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT