File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
longest-increasing-subsequence Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n * log n)
2+ // Space Complexity: O(n)
3+
4+ function lengthOfLIS ( nums : number [ ] ) : number {
5+ const sub : number [ ] = [ ] ; // O(n)
6+
7+ for ( const num of nums ) { // O(n)
8+ // lower bound binary search: find the first index where element >= target
9+ let left = 0 ;
10+ let right = sub . length ;
11+ const target = num ;
12+
13+ while ( left < right ) { // O(log n)
14+ let mid = Math . floor ( ( left + right ) / 2 ) ;
15+ if ( sub [ mid ] < target ) {
16+ left = mid + 1 ;
17+ } else {
18+ right = mid ;
19+ }
20+ }
21+
22+ // if target is greater than all elements in sub
23+ if ( left === sub . length ) {
24+ sub . push ( target ) ;
25+ } else {
26+ // replace the first element >= target
27+ sub [ left ] = target ;
28+ }
29+ }
30+
31+ return sub . length ;
32+ }
33+
You can’t perform that action at this time.
0 commit comments