Question

Give an O(n2 ) algorithm (Pseudocode) that, given a sequence S, finds the longest subsequence that...

Give an O(n2 ) algorithm (Pseudocode) that, given a sequence S, finds the longest subsequence that first increases then decreases.

For instance, in the sequence S = [10, 4, 5, 11, 2, 7, 4, 3, 9] the longest such subsequence is [4,5,11,7,4,3]. The subsequence does not have to be consecutive. (Hint: Use two arrays, one for increasing subsequences and the other for decreasing subsequences.)

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

function longestBitonicSequence( Array arr[], Integer n as size )

{

Integer i, j;

/* Allocate memory for LIS[] and initialize LIS values as 1 for

all indexes */

Array lis[n]

for i = 0 to n do

lis[i] = 1

end loop

/* Compute LIS values from left to right */

for i 1 to n-1 do

for j 0 to i-1 do

if (arr[i] > arr[j] && lis[i] < lis[j] + 1) then

lis[i] = lis[j] + 1

end if

end loop

end loop

/* Allocate memory for lds and initialize LDS values for

all indexes */

array lds[n];

for i = 0 to n do

lds[i] = 1

end loop

/* Compute LDS values from right to left */

for i = n-2 to 0 do

for j = n-1 to i+1 do

if (arr[i] > arr[j] && lds[i] < lds[j] + 1) then

lds[i] = lds[j] + 1

end if

end loop

end loop

/* Return the maximum value of lis[i] + lds[i] - 1*/

max = lis[0] + lds[0] - 1;

for i = 1 to n do

if (lis[i] + lds[i] - 1 > max) then

max = lis[i] + lds[i] - 1

end if

end loop

return max;

}

Add a comment
Know the answer?
Add Answer to:
Give an O(n2 ) algorithm (Pseudocode) that, given a sequence S, finds the longest subsequence that...
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
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