-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmaximumSumSubarray.js
More file actions
36 lines (33 loc) · 1.02 KB
/
maximumSumSubarray.js
File metadata and controls
36 lines (33 loc) · 1.02 KB
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
/*
This solution uses Kadane's Algorithm for the classic maximum subarray problem.
In this algorithm, you should do the following:
1. Track a running total for the array of numbers
2. Track the maximum total found so far
3. If the total + next number are greater than the maximum total so far, total equals maximum number
4. If the total becomes negative, reset total to 0
5. Return the maximum total when finished iterating through the array of numbers
*/
const findMaxSumSubarray = numberArray => {
if (!Array.isArray(numberArray)) {
return null;
}
if (!numberArray.length) {
return 0;
}
let maxTotal = null;
let currentTotal = 0;
numberArray.forEach(num => {
currentTotal += num;
if (currentTotal > -1 && (!maxTotal || currentTotal > maxTotal)) {
maxTotal = currentTotal;
}
if (currentTotal < 0) {
currentTotal = 0;
}
});
if (!maxTotal) {
return 0;
}
return maxTotal;
};
module.exports = findMaxSumSubarray;