Problem Summary
Given a sequence of integers, find the length of the longest increasing subsequence (LIS).
Solution 1: DP, O(N^2) time
Let us denote the given array with A[1], A[2], …, A[N].
Define f[i] as the length of the LIS ending at A[i]. So we have
f[i] = max{f[j]} + 1 , where j < i and A[j] < A[i]
The answer is max{f[i]}, i = 1,2,…,N. This method takes O(N^2) time and O(N) space.
Solution 2: DP + Binary Search, O(NlogN) time
Define g[i] as the minimal ending number of all increasing subsequences whose length are i.
Naturally, we realize that g[i] is non-decreasing, which means we can use binary search on it.
Plus, if g[l] has a legal value, the answer L is equal to or greater than l.That is, L = max{l}, where g[l] has a legal value.
These thoughts lead to the following algorithm:
First, we initialize g[1] with A[1] and L with 1.
Then we iterate through the array. For each i,
- If A[i] > g[L], it is a great thing because we can now increase L by 1. For new L, we let g[L] = A[i].
- If A[i] == g[L], A[i] is not helpful so we continue.
- If A[i] < g[L], we use binary search to find an index k, such that g[k-1] < A[i] ≤ g[k]. (We suppose g[0] is INT_MIN, so there will always be a legal k.) Then we use A[i] to update g[k].
This method has a lower time complexity, but also requires more thinking.
Code for Soluton 2
|
|