Skip to content

Commit dbd639f

Browse files
committed
Add maxSubarray
1 parent 527d9eb commit dbd639f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

snippets/maxSubarray.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
---
2+
title: Maximum subarray
3+
tags: algorithm,math,array
4+
expertise: intermediate
5+
firstSeen: 2022-09-07T05:00:00-04:00
6+
---
7+
8+
Finds a contiguous subarray with the largest sum within an array of numbers.
9+
10+
- Use a greedy approach to keep track of the current `sum` and the current maximum, `maxSum`. Set `maxSum` to `-Infinity` to make sure that the highest negative value is returned, if all values are negative.
11+
- Define variables to keep track of the maximum start index, `sMax`, maximum end index, `eMax` and current start index, `s`.
12+
- Use `Array.prototype.forEach()` to iterate over the values and add the current value to the `sum`.
13+
- If the current `sum` is greater than `maxSum`, update the index values and the `maxSum`.
14+
- If the `sum` is below `0`, reset it to `0` and update the value of `s` to the next index.
15+
- Use `Array.prototype.slice()` to return the subarray indicated by the index variables.
16+
17+
```js
18+
const maxSubarray = (...arr) => {
19+
let maxSum = -Infinity,
20+
sum = 0;
21+
let sMax = 0,
22+
eMax = arr.length - 1,
23+
s = 0;
24+
25+
arr.forEach((n, i) => {
26+
sum += n;
27+
if (maxSum < sum) {
28+
maxSum = sum;
29+
sMax = s;
30+
eMax = i;
31+
}
32+
33+
if (sum < 0) {
34+
sum = 0;
35+
s = i + 1;
36+
}
37+
});
38+
39+
return arr.slice(sMax, eMax + 1);
40+
};
41+
42+
```
43+
44+
```js
45+
maxSubarray(-2, 1, -3, 4, -1, 2, 1, -5, 4); // [4, -1, 2, 1]
46+
```

0 commit comments

Comments
 (0)