Poison

300. Longest Increasing Subsequence

DP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int lengthOfLIS(int[] nums) {
int maxLength = 1;

// 定义 dp[i] 为以 nums[i] 结尾的最长严格递增子序列的长度
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);

for (int i = 1; i < nums.length; i++) {
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;
}
}
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
class Solution {
public int lengthOfLIS(int[] nums) {
// 定义 tails 数组,tails[i] 为长度为 i + 1 的严格递增子序列且 tails[i] 尽可能小
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[] tails, int left, int right, int target) {
while (left <= right) {
int mid = (left + right) >>> 1;
if (tails[mid] < target) {
left = mid + 1;
} else if (tails[mid] > target) {
right = mid - 1;
} else {
right = mid - 1;
}
}

// now: right, left
return left;
}
}
Reference

300. Longest Increasing Subsequence