Skip to content

Commit 0758db7

Browse files
Add "Maximum subarray sum" kata
1 parent c00a311 commit 0758db7

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

5-kyu/maximum-subarray-sum.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<h1>Maximum subarray sum <sup><sup>5 Kyu</sup></sup></h1>
2+
3+
<sup>
4+
<a href="https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c">
5+
<strong>LINK TO THE KATA</strong>
6+
</a> - <code>ALGORITHMS</code> <code>LISTS</code> <code>DYNAMIC PROGRAMMING</code> <code>FUNDAMENTALS</code> <code>PERFORMANCE</code>
7+
</sup>
8+
9+
## Description
10+
11+
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
12+
13+
```javascript
14+
maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
15+
// should be 6: [4, -1, 2, 1]
16+
```
17+
18+
Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
19+
20+
Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
21+
22+
## Solution
23+
24+
```javascript
25+
const maxSequence = arr => {
26+
let maxSoFar = 0
27+
let maxEndingHere = 0
28+
29+
for (let i = 0; i < arr.length; i++) {
30+
maxEndingHere += arr[i]
31+
32+
if (maxEndingHere < 0) maxEndingHere = 0
33+
34+
if (maxSoFar < maxEndingHere) maxSoFar = maxEndingHere
35+
}
36+
37+
return maxSoFar
38+
}
39+
```

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ JavaScript katas on Codewars are programming challenges that help you improve yo
4141
- **[Greed is Good](./5-kyu/greed-is-good.md)**<br><sup>`ALGORITHMS`</sup>
4242
- **[Human Readable Time](./5-kyu/human-readable-time.md)**<br><sup>`DATE TIME` `MATHEMATICS` `ALGORITHMS`</sup>
4343
- **[Josephus Survivor](./5-kyu/josephus-survivor.md)**<br><sup>`MATHEMATICS` `COMBINATORICS` `ALGORITHMS` `LISTS` `ARRAYS`</sup>
44+
- **[Maximum subarray sum](./5-kyu/maximum-subarray-sum.md)**<br><sup>`ALGORITHMS` `LISTS` `DYNAMIC PROGRAMMING` `FUNDAMENTALS` `PERFORMANCE`</sup>
4445
- **[Mean Square Error](./5-kyu/mean-square-error.md)**<br><sup>`ARRAYS` `MATHEMATICS` `ALGORITHMS`</sup>
4546
- **[Moving Zeros To The End](./5-kyu/moving-zeros-to-the-end.md)**<br><sup>`ARRAYS` `SORTING` `ALGORITHMS`</sup>
4647
- **[Not very secure](./5-kyu/not-very-secure.md)**<br><sup>`REGULAR EXPRESSIONS` `STRINGS`</sup>

0 commit comments

Comments
 (0)