Problem
Given a sequence of integers, find the longest increasing subsequence (LIS).
You code should return the length of the LIS.
Clarification
What's the definition of longest increasing subsequence?
The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.
https://en.wikipedia.org/wiki...
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
Challenge
Time complexity O(n^2) or O(nlogn)
Solution
DP O(n^2)
public class Solution {
public int longestIncreasingSubsequence(int[] nums) {
int n = nums.length, max = 0;
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
dp[i] = nums[i] >= nums[j] ? Math.max(dp[j]+1, dp[i]) : dp[i];
max = Math.max(max, dp[i]);
}
}
return max;
}
}
Binary Search O(nlogn)
public class Solution {
public int longestIncreasingSubsequence(int[] nums) {
int n = nums.length, max = 0;
if (n == 0) return 0;
int[] tails = new int[nums.length];
tails[0] = nums[0];
int index = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < tails[0]) tails[0] = nums[i];
else if (nums[i] >= tails[index]) tails[++index] = nums[i];
else tails[bisearch(tails, 0, index, nums[i])] = nums[i];
}
return index+1;
}
public int bisearch(int[] tails, int start, int end, int target) {
while (start <= end) {
int mid = start + (end-start)/2;
if (tails[mid] == target) return mid;
else if (tails[mid] < target) start = mid+1;
else end = mid-1;
}
return start;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。