Skip to content

Commit 18344dc

Browse files
author
Mauricio Klein
committed
Add solution for challenge #43
1 parent 54e08d7 commit 18344dc

File tree

6 files changed

+45
-0
lines changed

6 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,4 @@
4242
- [x] [Challenge 40: Queue Using Two Stacks](challenge-40/)
4343
- [x] [Challenge 41: Maximum sequence of consecutive numbers](challenge-41/)
4444
- [x] [Challenge 42: Depth of a stringified binary tree](challenge-42/)
45+
- [x] [Challenge 43: Contiguous Subarray with Maximum Sum](challenge-43/)

challenge-43/Makefile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-43/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Contiguous Subarray with Maximum Sum
2+
3+
This problem was asked by Twitter.
4+
5+
## Description
6+
7+
You are given an array of integers. Find the maximum sum of all possible contiguous subarrays of the array.
8+
9+
*Your solution should run in linear time.*
10+
11+
## Example
12+
```
13+
Input: [34, -50, 42, 14, -5, 86]
14+
Output: 137 ([42, 14, -5, 86])
15+
```

challenge-43/__init__.py

Whitespace-only changes.

challenge-43/solver.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#
2+
# Time complexity: O(n)
3+
# Space complexity: O(1)
4+
#
5+
def max_subarray(nums):
6+
# Kadane's algorithm
7+
current_sum, max_sum = 0, 0
8+
9+
for num in nums:
10+
current_sum = max(0, current_sum + num)
11+
max_sum = max(max_sum, current_sum)
12+
13+
return max_sum

challenge-43/test_solver.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import unittest
2+
from solver import max_subarray
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_max_subarray(self):
6+
self.assertEqual(max_subarray([34, -50, 42, 14, -5, 86]), 137) # Max sum is given by "[42, 14, -5, 86]"
7+
self.assertEqual(max_subarray([-1, -2, -3 ]), 0) # Max sum is given by "[]"
8+
self.assertEqual(max_subarray([-1, 1, 1, 1, -1, 4, -1 ]), 6) # Max sum is given by "[1, 1, 1, -1, 4]"
9+
self.assertEqual(max_subarray([ ]), 0) # Max sum is given by "[]"
10+
11+
if __name__ == "__main__":
12+
unittest.main()

0 commit comments

Comments
 (0)