Professional Documents
Culture Documents
Longest Increasing Subsequence
Longest Increasing Subsequence
CSCI 3104
April 14, 2013
1:
2:
3:
4:
5:
6:
7:
p4 ={7 }
which was given a back-pointer to 3 from the very first pile. Thus,
concatenating these numbers in reverse, we have
bn ={3, 4, 6,7 }
which can easily be verified as the longest increasing subsequence in
our original an . Notice that this will only work if each pointer remains
unaltered after its initial assignment.
Here is accompanying pseudocode for the algorithm:
ALGORITHM LongestIncreasingSubsequence(A[1, , n])
// Finds the length of the subsequence of the given array of
maximum length,
// along with one such subsequence
// Input: Array A[1, , n] of distinct elements (A.size > 0)
// Output: Array B[1, , m] of the longest increasing
subsequence of A
Initialize list of piles (array or list)
Add A[0] to Heap #1
for i := 1, , n
for each existing heap
if A[i] < top card of heap
add A[i] to heap
A[i].previous := top card of previous heap
else create new heap; add A[i] to new heap
pointer := top card of last pile
B[0] := pointer
j := 1
while pointer != null
pointer := pointer.previous
B[j] := pointer
j := j + 1
reverse the order of the elements in B
return B
What is the time and space complexity of this algorithm?
Observe that the innermost loop is executed for each element in the
original list, and for each current pile. Thus, in the worst case, a new
pile is created with each iteration, and so the number of comparisons is
estimated as follows:
n
n
n
n(n+ 1) n(n+ 1) n
n2 (n+1)
j= 2 = 2 1= 2 O(n 3)
i=1 j=1
i=1
i=1
Thus, the algorithm carries a cubic worst-case time complexity. This
also assumes that creating a new pile runs in constant time. In the best
case, we only have one pile the entire algorithm, and so the number of
comparisons would roughly be
1=n O(n)
i=1