Skip to content

Commit 854c02d

Browse files
committed
✨ [53] a1 - After watching explained on YT
Runtime 91 ms Beats 18.60% Memory 50.4 MB Beats 48.48%
1 parent 801a919 commit 854c02d

File tree

3 files changed

+77
-5
lines changed

3 files changed

+77
-5
lines changed

53/my_solution.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const maxSubArray = (nums) => {
6+
let tmpMax = 0, max = 0;
7+
8+
for (let i = 0; i < nums.length; i++) {
9+
if (0 === i) {
10+
tmpMax = nums[i];
11+
max = tmpMax;
12+
continue;
13+
}
14+
15+
// if c > m, restart m
16+
if (0 >= tmpMax && nums[i] > tmpMax) {
17+
console.log(nums[i] + " is nbiggger!")
18+
console.log(tmpMax)
19+
console.log(tmpMax + nums[i])
20+
21+
// when pre max and curr value sum is more than max, we restart max
22+
if ((tmpMax + nums[i]) > max) { // c + m > max - restart the max
23+
tmpMax = nums[i];
24+
max = tmpMax;
25+
} else { // but in the case where pre = -2 and current = - 1 and they are smaller than max, we reset the max if curr (tmpMax) is bigger than max, in this case -1 > -2, so replace.
26+
console.log("WTF?")
27+
tmpMax = nums[i];
28+
if (tmpMax > max) max = tmpMax;
29+
30+
}
31+
} else {
32+
tmpMax += nums[i];
33+
if (tmpMax > max) max = tmpMax;
34+
}
35+
}
36+
37+
console.log("max")
38+
console.log(max)
39+
40+
return max;
41+
};
42+
43+
// maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
44+
// maxSubArray([5, 4, -1, 7, 8])
45+
// maxSubArray([2, 5, 9, 2, 6, 8, -10])
46+
// maxSubArray([-2, -1])
47+
// maxSubArray([1, -1])
48+
// maxSubArray([-11, -1])
49+
maxSubArray([3, -3, 2, -3]) // 3

53/solution.js

+23
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,28 @@
33
* @return {number}
44
*/
55
const maxSubArray = (nums) => {
6+
let tmpMax = 0, max = 0;
67

8+
for (let i = 0; i < nums.length; i++) {
9+
if (0 === i) {
10+
tmpMax = nums[i];
11+
max = tmpMax;
12+
continue;
13+
}
14+
15+
if (0 >= tmpMax && nums[i] > tmpMax) {
16+
if ((tmpMax + nums[i]) > max) {
17+
tmpMax = nums[i];
18+
max = tmpMax;
19+
} else {
20+
tmpMax = nums[i];
21+
if (tmpMax > max) max = tmpMax;
22+
}
23+
} else {
24+
tmpMax += nums[i];
25+
if (tmpMax > max) max = tmpMax;
26+
}
27+
}
28+
29+
return max;
730
};

README.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ iex ./.../solution.ex
5050

5151
Quick create in bash
5252
```ssh
53-
chapter=53 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js
54-
55-
# TODO: And TOC above
56-
57-
alias x="node ./$chapter/my_solution"
53+
chapter=53 && mkdir ./$chapter && touch ./$chapter/my_solution.js && touch ./$chapter/solution.js && alias x="node ./$chapter/my_solution"
5854
```
55+
56+
<!--
57+
TODO: Add to TOC!
58+
-->

0 commit comments

Comments
 (0)