|
6 | 6 | * @return {Number[]}
|
7 | 7 | */
|
8 | 8 | export default function dpMaximumSubarray(inputArray) {
|
9 |
| - // We iterate through the inputArray once, using a greedy approach |
10 |
| - // to keep track of the maximum sum we've seen so far and the current sum |
| 9 | + // We iterate through the inputArray once, using a greedy approach to keep track of the maximum |
| 10 | + // sum we've seen so far and the current sum. |
11 | 11 | //
|
12 |
| - // currentSum gets reset to 0 everytime it drops below 0 |
| 12 | + // The currentSum variable gets reset to 0 every time it drops below 0. |
13 | 13 | //
|
14 |
| - // maxSum is set to -Infinity so that if all numbers |
15 |
| - // are negative, the highest negative number will constitute |
16 |
| - // the maximum subarray |
| 14 | + // The maxSum variable is set to -Infinity so that if all numbers are negative, the highest |
| 15 | + // negative number will constitute the maximum subarray. |
| 16 | + |
17 | 17 | let maxSum = -Infinity;
|
18 | 18 | let currentSum = 0;
|
19 | 19 |
|
20 |
| - // We need to keep track of the starting and ending indices that |
21 |
| - // contributed to our maxSum so that we can return the actual subarray |
| 20 | + // We need to keep track of the starting and ending indices that contributed to our maxSum |
| 21 | + // so that we can return the actual subarray. |
22 | 22 | let maxStartIndex = 0;
|
23 | 23 | let maxEndIndex = inputArray.length;
|
| 24 | + |
24 | 25 | let currentStartIndex = 0;
|
25 | 26 |
|
26 |
| - inputArray.forEach((num, currentIndex) => { |
27 |
| - currentSum += num; |
| 27 | + inputArray.forEach((currentNumber, currentIndex) => { |
| 28 | + currentSum += currentNumber; |
28 | 29 |
|
29 |
| - // Update maxSum and the corresponding indices |
30 |
| - // if we have found a new max |
| 30 | + // Update maxSum and the corresponding indices if we have found a new max. |
31 | 31 | if (maxSum < currentSum) {
|
32 | 32 | maxSum = currentSum;
|
33 | 33 | maxStartIndex = currentStartIndex;
|
34 | 34 | maxEndIndex = currentIndex + 1;
|
35 | 35 | }
|
36 | 36 |
|
37 |
| - // Reset currentSum and currentStartIndex |
38 |
| - // if currentSum drops below 0 |
| 37 | + // Reset currentSum and currentStartIndex if currentSum drops below 0. |
39 | 38 | if (currentSum < 0) {
|
40 | 39 | currentSum = 0;
|
41 | 40 | currentStartIndex = currentIndex + 1;
|
|
0 commit comments