Longest Increasing Subsequence
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.
Example
For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3
For [4, 2, 4, 5, 3, 7], the LIS is [2, 4, 5, 7], return 4
Notes:
Coordinate DP
- State: f[i], the longest increasing subsequence to i
- initialize: f[i] = 1
- function: Max(f[j]+1) when nums[i] > nums[j], j from 0 to i-1
- answer: max f[i]
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
// state
int[] f = new int[nums.length];
// initialize
f[0] = 1;
// function
int max = 1;
for (int i = 1; i < nums.length; ++i) {
f[i] = 1;
for (int j = i-1; j >= 0; --j) {
if (nums[i] > nums[j]) {
f[i] = Math.max(f[i], f[j] + 1);
}
}
max = Math.max(max, f[i]);
}
// answer
return max;
}