-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_solution.js
58 lines (48 loc) · 1.45 KB
/
my_solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @param {number[]} nums
* @return {number}
*/
const maxSubArray = (nums) => {
let tmpMax = nums[0], max = nums[0];
for (let i = 1; i < nums.length; i++) {
if (tmpMax < 0) tmpMax = 0;
tmpMax += nums[i];
if (tmpMax > max) max = tmpMax;
}
console.log("max")
console.log(max)
return max;
};
const maxSubArrayOld = (nums) => {
let tmpMax = nums[0], max = nums[0];
for (let i = 1; i < nums.length; i++) {
// if c > m, restart m
if (0 >= tmpMax && nums[i] > tmpMax) {
// console.log(nums[i] + " is nbiggger!")
// console.log(tmpMax)
// console.log(tmpMax + nums[i])
// when pre max and curr value sum is more than max, we restart max
if ((tmpMax + nums[i]) > max) { // c + m > max - restart the max
tmpMax = nums[i];
max = tmpMax;
} 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.
console.log("WTF?")
tmpMax = nums[i];
if (tmpMax > max) max = tmpMax;
}
} else {
tmpMax += nums[i];
if (tmpMax > max) max = tmpMax;
}
}
console.log("max")
console.log(max)
return max;
};
maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
// maxSubArray([5, 4, -1, 7, 8])
// maxSubArray([2, 5, 9, 2, 6, 8, -10])
// maxSubArray([-2, -1])
// maxSubArray([1, -1])
// maxSubArray([-11, -1])
// maxSubArray([3, -3, 2, -3]) // 3