Skip to content

Commit 06ac2fa

Browse files
committed
4. Longest Increasing Subsequence
1 parent d71b70a commit 06ac2fa

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* 1. dfs -> time limited
5+
* 2. memoization + dfs
6+
*
7+
* n: length of nums
8+
* time complexity: O(n^2)
9+
* space complexity: O(n)
10+
*/
11+
var lengthOfLIS = function (nums) {
12+
const memo = new Array(nums.length).fill(-1);
13+
let answer = 0;
14+
15+
const dfs = (index) => {
16+
if (memo[index] !== -1) return memo[index];
17+
18+
let maxLength = 1;
19+
20+
for (let i = index + 1; i < nums.length; i++) {
21+
if (nums[index] < nums[i]) {
22+
maxLength = Math.max(maxLength, 1 + dfs(i));
23+
}
24+
}
25+
26+
memo[index] = maxLength;
27+
return maxLength;
28+
};
29+
30+
for (let i = 0; i < nums.length; i++) {
31+
answer = Math.max(answer, dfs(i));
32+
}
33+
34+
return answer;
35+
};

0 commit comments

Comments
 (0)