-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestIncreasingSubsequence.ts
More file actions
59 lines (43 loc) · 1.36 KB
/
Copy pathlongestIncreasingSubsequence.ts
File metadata and controls
59 lines (43 loc) · 1.36 KB
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
49
50
51
52
53
54
55
56
57
58
59
/*
Given an integer array nums, return the length of the longest strictly increasing subsequence.
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
*/
function lengthOfLIS(nums: number[]): number {
// Approach 1: Brute force
// backtracking all the subsequence
const maxLengths = new Array(nums.length).fill(1);
for (let index = 1; index < nums.length; index++) {
for (let subIndex = 0; subIndex < index; subIndex++) {
if (nums[subIndex] < nums[index]) {
maxLengths[index] = Math.max(maxLengths[index], maxLengths[subIndex] + 1);
}
}
}
return Math.max(...maxLengths);
}
function lengthOfLISWithBinarySearch(nums: number[]): number {
// Approach 2: Patience sorting with binary search — O(n log n)
// tails[i] = smallest tail of all increasing subsequences of length i+1
const tails: number[] = [];
for (const num of nums) {
let left = 0, right = tails.length;
while (left < right) {
const middle = (left + right) >> 1;
if (tails[middle] < num) left = middle + 1;
else right = middle;
}
tails[left] = num; // replace or append
}
console.log(tails);
return tails.length;
}
console.log(lengthOfLISWithBinarySearch([0, 1, 0, 3, 2, 3]));