Skip to content

Commit 15e6bb8

Browse files
authored
[Sehwan] Week12 solution with JavaScript (DaleStudy#192)
* Added solutions * Added jump game solution
1 parent 381a61a commit 15e6bb8

File tree

5 files changed

+85
-0
lines changed

5 files changed

+85
-0
lines changed

jump-game/nhistory.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var canJump = function (nums) {
2+
let pointer = 0;
3+
for (let i = 0; i < nums.length; i++) {
4+
if (i > pointer) return false;
5+
pointer = Math.max(pointer, i + nums[i]);
6+
if (pointer >= nums.length - 1) return true;
7+
}
8+
return false;
9+
};
10+
11+
// TC: O(n)
12+
// SC: O(1)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var longestCommonSubsequence = function (text1, text2) {
2+
// Edge case
3+
if (text1.length === 1 && text2.length === 1 && text1 === text2) return 1;
4+
5+
let dp = Array.from({ length: text1.length + 1 }, () =>
6+
Array(text2.length + 1).fill(0)
7+
);
8+
9+
for (let i = 1; i <= text1.length; i++) {
10+
for (let j = 1; j <= text2.length; j++) {
11+
if (text1[i - 1] === text2[j - 1]) {
12+
dp[i][j] = dp[i - 1][j - 1] + 1;
13+
} else {
14+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
15+
}
16+
}
17+
}
18+
19+
return dp[text1.length][text2.length];
20+
};
21+
22+
// m = text1.length | n = text2.length
23+
// TC: O(m*n)
24+
// SC: O(m*n)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
var lengthOfLIS = function (nums) {
2+
if (nums.length === 1) return 1;
3+
let dp = new Array(nums.length).fill(1);
4+
5+
for (let i = 0; i < nums.length; i++) {
6+
for (let j = 0; j < i; j++) {
7+
if (nums[i] > nums[j]) {
8+
dp[i] = Math.max(dp[i], dp[j] + 1);
9+
}
10+
}
11+
}
12+
return Math.max(...dp);
13+
};
14+
15+
// TC: O(n^2)
16+
// SC: O(n)

maximum-subarray/nhistory.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
var maxSubArray = function (nums) {
2+
// Edge case
3+
if (nums.length === 1) return nums[0];
4+
5+
let maxSum = nums[0];
6+
let curSum = nums[0];
7+
8+
for (let i = 1; i < nums.length; i++) {
9+
curSum = Math.max(nums[i], curSum + nums[i]);
10+
maxSum = Math.max(maxSum, curSum);
11+
}
12+
13+
return maxSum;
14+
};
15+
16+
// TC: O(n)
17+
// SC: O(1)

unique-paths/nhistory.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
var uniquePaths = function (m, n) {
2+
// Edge case
3+
if (m === 1 || n === 1) return 1;
4+
5+
let rowArr = new Array(n).fill(1);
6+
7+
for (let row = 1; row < m; row++) {
8+
for (let col = 1; col < n; col++) {
9+
rowArr[col] += rowArr[col - 1];
10+
}
11+
}
12+
return rowArr[n - 1];
13+
};
14+
15+
// TC: O(m*n)
16+
// SC: O(n)

0 commit comments

Comments
 (0)