Skip to content

Commit ec041f9

Browse files
committed
Add longest-increasing-subsequence solution
1 parent b64d18b commit ec041f9

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
// Time Complexity: O(n^)
7+
// Space Complexity: O(n)
8+
var lengthOfLIS = function (nums) {
9+
if (nums.length === 0) {
10+
return 0;
11+
}
12+
13+
let dp = new Array(nums.length).fill(1); // dp[i] will be the length of LIS ending at i
14+
15+
for (let i = 1; i < nums.length; i++) {
16+
for (let j = 0; j < i; j++) {
17+
if (nums[i] > nums[j]) {
18+
// Strictly increasing condition
19+
dp[i] = Math.max(dp[i], dp[j] + 1);
20+
}
21+
}
22+
}
23+
24+
return Math.max(...dp); // The length of the longest subsequence
25+
};
26+

0 commit comments

Comments
 (0)