Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(nlog(n)) time complexity?
DP solution with O(N^2) complexity
int lengthOfLIS(vector<int>& nums) {
// This will be our array to track longest sequence length
int dp[nums.size()];
// Fill each position with value 1 in the array
for (int i=0; i<nums.size(); i++)
dp[i] = 1;
// Mark one pointer at i. For each i, start from j=0.
for (int i=1; i<nums.size(); i++) {
for (int j=0; j<i; j++) {
// It means next number contributes to increasing sequence.
if (nums[j] < nums[i]) {
// But increase the value only if it results in a larger value of the sequence than dp[i]
// It is possible that dp[i] already has larger value from some previous j'th iteration
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
// Find the maximum length from the array that we just generated
int res = 0;
for (int i=0; i<nums.size(); i++)
res = max(res, dp[i]);
return res;
}
9 lines C++ code with O(NlogN) complexity
int lengthOfLIS(vector<int>& nums) {
vector<int> res;
for (int x : nums) {
auto it = lower_bound(res.begin(), res.end(), x);
if (it == res.end()) res.push_back(x);
else *it = x;
}
return res.size();
}
More details
https://discuss.leetcode.com/topic/30721/my-easy-to-understand-o-n-2-solution-using-dp-with-video-explanation
https://discuss.leetcode.com/topic/28696/9-lines-c-code-with-o-nlogn-complexity/12
http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/