forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_subarray_sum.py
More file actions
56 lines (41 loc) · 1.3 KB
/
max_subarray_sum.py
File metadata and controls
56 lines (41 loc) · 1.3 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
Maximum subarray sum
The subarray must be contiguous.
Sample input: [-2, -3, 4, -1, -2, 1, 5, -3]
Sample output: 7
Output explanation: [4, -1, -2, 1, 5]
=========================================
Need only one iteration, in each step add the current element to the current sum.
When the sum is less than 0, reset the sum to 0 and continue with adding. (we care only about non-negative sums)
After each addition, check if the current sum is greater than the max sum. (Called Kadane's algorithm)
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def max_subarray_sum(a):
curr_sum = 0
max_sum = 0
for val in a:
# extend the current sum with the curren value;
# reset it to 0 if it is smaller than 0, we care only about non-negative sums
curr_sum = max(0, curr_sum + val)
# check if this is the max sum
max_sum = max(max_sum, curr_sum)
return max_sum
###########
# Testing #
###########
# Test 1
# Correct result => 7
print(max_subarray_sum([-2, -3, 4, -1, -2, 1, 5, -3]))
# Test 2
# Correct result => 5
print(max_subarray_sum([1, -2, 2, -2, 3, -2, 4, -5]))
# Test 3
# Correct result => 7
print(max_subarray_sum([-2, -5, 6, -2, -3, 1, 5, -6]))
# Test 4
# Correct result => 0
print(max_subarray_sum([-6, -1]))