DP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public int lengthOfLIS(int[] nums) { int maxLength = 1;
int[] dp = new int[nums.length];
for (int i = 0; i < nums.length; i++) { dp[i] = 1; for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) { dp[i] = Math.max(dp[i], dp[j] + 1); } }
maxLength = Math.max(maxLength, dp[i]); }
return maxLength; } }
|
DP + Binary Search
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
| class Solution { public int lengthOfLIS(int[] nums) { int[] tails = new int[nums.length]; int nextIndex = 0;
for (int num : nums) { int insertIndex = findInsertIndex(tails, 0, nextIndex - 1, num); tails[insertIndex] = num; if (insertIndex == nextIndex) { nextIndex++; } }
return nextIndex; }
private int findInsertIndex(int[] nums, int left, int right, int target) {
while (left <= right) { int mid = (left + right) >>> 1; if (target > nums[mid]) { left = mid + 1; } else { right = mid - 1; } }
return left; } }
|
References
300. Longest Increasing Subsequence