Longest Ascending Subsequence I & II
Given an array A[0]...A[n-1] of integers, find out the longest ascending subsequence.
Solution: Memoize longest subsequence at index, memoize previous step index of sequence
TC: O(N^2)
SC: O(2N) = O(N) M and prev array
More insane solution: Patience Sort
High Level: Use piles of descending sequences to track length of longest sub-sequence.
Sorting rule: Solitaire style. Place current card in the left most pile, such that it forms a decreasing sequence with that pile.
Why is the number of piles the length of the longest subsequence?
Whenever a new card is placed, it can only form a new pile if every pile to its left ends in a number smaller than the new card.
example:
Since the bottom card of each pile forms an increasing array, we can binary search the placement of each new card.
TC: NLogN
SC: N
Last updated
Was this helpful?