-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmax-sum-subarray.js
More file actions
executable file
·33 lines (24 loc) · 944 Bytes
/
max-sum-subarray.js
File metadata and controls
executable file
·33 lines (24 loc) · 944 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
/* It is an adaptation of Kadane's algorithm;
It has O(n) linear complexity;
Using 'temp' and 'result' objects results in high readability and more concise code. */
const maxSequence = arr => {
const allPositives = arr => arr.every(n => n > 0);
const allNegatives = arr => arr.every(n => n < 0);
if(arr.length === 0 || allNegatives(arr)) return 0;
const temp = { start: 0, sum: 0 };
let result = { start: 0, end: 0, sum: 0 };
for (let i = 0; i < arr.length; i++) {
temp.sum += arr[i];
if (temp.sum > result.sum) {
result = { start: temp.start, end: i, sum: temp.sum };
}
if (temp.sum < 0) {
temp.sum = 0;
temp.start = i + 1;
}
}
return result;
};
console.log(maxSequence([-2, -1, -3, -4, -1, -2, -1, -5, -4])); // 0
console.log(maxSequence([])); // 0
console.log(maxSequence([2, 1, 3, 4, 1, 2, 1, 5, 4])); // { start: 0, end: 8, sum: 23 }