-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path42-arrayMaxSubSum.js
More file actions
42 lines (39 loc) · 929 Bytes
/
42-arrayMaxSubSum.js
File metadata and controls
42 lines (39 loc) · 929 Bytes
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
function getMaxSubSum(array) {
let maxSubSum = 0;
for (let i = 0; i < array.length; i++) {
let sumFixedStart = 0;
for (let j = i; j < array.length; j++) {
sumFixedStart += array[j];
maxSubSum = Math.max(maxSubSum, sumFixedStart);
}
}
return maxSubSum;
}
const result2 = getMaxSubSum([-1, 2, 3, -9, 11]);
console.log(result2);
// optimzed solution in O(n)
function getMaxSubSum2(array) {
let maxSum = 0;
let partialSum = 0;
for (let item of array) {
partialSum += item;
maxSum = Math.max(maxSum, partialSum);
if (partialSum < 0) partialSum = 0;
}
return maxSum;
}
const result1 = getMaxSubSum2([-1, 2, 3, -9]);
// console.log(result1);
// solution 3
function sol3(arr) {
let subSum = [];
for (let i = 0; i < arr.length; i++) {
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
subSum.push(sum);
}
}
return Math.max(...subSum);
}
console.log(sol3([1, -3, 2, 1, -1]));