Tuesday, February 28, 2012

Dynamic Programming: Longest increasing subsequence


Given a unordered array of numbers, remove the fewest number of numbers to produce the longest ordered sequence. Print count of fewest numbers to be removed, and the remaining sequence. For example, if input is 1 2 3 4 5 6 7 8 9 10, no (zero) numbers are removed, and input is the longest sequence. If input is, 1 2 3 8 10 5 6 7 12 9 4 0, then fewest number of elements to be removed is 5 is the fewest number to be removed, and the longest sequence is 1 2 3 5 6 7 12.



Recurrence.
For 1 <= i <= n,
A(i) = 1 + max{A(j) | 1 <= j < i and aj < ai}.
(We assume max(NULL) == 0.)


Time complexity: O(n2). 


Code input/output:
int [] A = {7, 3, 8, 4, 6};

LIS ends at: 4
MaxLength of LIS:3
Printing DP array: 
1 1 2 2 3 
Printing Previous Array:
-1 -1 1 1 3 
Printing LongestIncreasingSubsequence:
3 4 6 
Fewest numbers to be removed to produce the Longest ordered subsequence:2


int [] B = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
LIS ends at: 15
MaxLength of LIS:6
Printing DP array: 
1 2 2 3 2 3 3 4 2 4 3 5 3 5 4 6 
Printing Previous Array:
-1 0 0 2 0 4 4 6 0 6 8 9 8 9 12 13 
Printing LongestIncreasingSubsequence:
0 2 6 9 11 15 
Fewest numbers to be removed to produce the Longest ordered subsequence:10


No comments:

Post a Comment