Skip to content

Commit 61e16db

Browse files
committed
longest increasing subsequence solution
- using binary search, lower bound
1 parent e53c316 commit 61e16db

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

longest-increasing-subsequence/hyer0705.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,33 @@
1+
// using binary search, lower bound
2+
function lengthOfLIS(nums: number[]): number {
3+
const n = nums.length;
4+
const sub: number[] = [];
5+
6+
for (const num of nums) {
7+
if (sub.length === 0 || num > sub[sub.length - 1]) {
8+
sub.push(num);
9+
} else if (num <= sub[sub.length - 1]) {
10+
let l = 0;
11+
let r = sub.length - 1;
12+
13+
while (l < r) {
14+
const mid = Math.floor((l + r) / 2);
15+
16+
if (num <= sub[mid]) {
17+
r = mid;
18+
} else {
19+
l = mid + 1;
20+
}
21+
}
22+
23+
sub[l] = num;
24+
}
25+
}
26+
27+
return sub.length;
28+
}
29+
30+
// using dp
131
function lengthOfLIS(nums: number[]): number {
232
const n = nums.length;
333
const dp: number[] = Array(n).fill(1);

0 commit comments

Comments
 (0)