300_ Longest Increasing Subsequence
[Medium][Dynamic Programming, Binary Search]
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Solution 1:
Idea:
If we know the lengths of longest increasing subsequence that end at indices 0, 1, 2, n-1, and we want to know the longest increasing subsequence that ends at index n, what shall we do?
We should look for look for the longest subsequence ending at any indices 0, 1, 2, n-1 whose value is less than the value at index n. Then this max length plus one will be the answer.
If there is no values in front of index n that is less than value at index n, the max length at index n is 1.
The max length for the entire array is the max of max length at all the indices.
Can be written in iterative or recursive fashion.
Time Complexity:
Space Complexity:
Iterative:
Recursive: (slow)
Solution 2:
Idea:
Our strategy determined by the following conditions:
If A[i] is smallest among all end candidates of active lists, we will start new active list of length 1.
If A[i] is largest among all end candidates of active lists, we will clone the largest active list, and extend it by A[i].
If A[i] is in between, we will find a list with largest end element that is smaller than A[i]. Clone and extend this list by A[i]. We will discard all other lists of same length as that of this modified list.
Note that at any instance during our construction of active lists, the following condition is maintained.
“end element of smaller list is smaller than end elements of larger lists”.
Refer to here
Time Complexity:
Space Complexity:
Last updated