LintCode/Longest Increasing Subsequence

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,

  1. 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].
  2. If A[i] == g[L], A[i] is not helpful so we continue.
  3. 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
/*
* @param nums: An integer array
* @return: The length of LIS (longest increasing subsequence)
*/
int longestIncreasingSubsequence(vector<int> &nums) {
int n = nums.size();
if (n<2)
return n;
int f[n+2];
f[1] = nums[0];
int len = 1;
for (int i = 1; i < n; ++i)
{
if (nums[i] > f[len])
f[++len] = nums[i];
else
if (nums[i] == f[len])
continue;
else
{
int pos = binary_search(nums[i],len,f);
f[pos] = nums[i];
}
}
return len;
}
int binary_search(int cur,int size,int *f) /* return k, s.t. f[k-1] < cur <= f[k] */
{
int l = 1, r = size;
while (l<r)
{
int mid = l + ((r-l)>>1);
if (f[mid] == cur)
return mid;
else
if (f[mid] < cur)
l = mid+1;
else
r = mid;
}
return l;
}
};