Skip to content

Commit efa5b8e

Browse files
committed
Add Kadane's algorithm for maximum subarray sum
1 parent 02680c9 commit efa5b8e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
Kadane's Algorithm: Given an array of integers, find the contiguous subarray
3+
with the largest sum.
4+
5+
Example:
6+
[-2, 1, -3, 4, -1, 2, 1, -5, 4] --> 6 (subarray [4, -1, 2, 1])
7+
"""
8+
9+
10+
def kadanes_algorithm(arr: list[int]) -> int:
11+
"""
12+
Finds the maximum sum of a contiguous subarray using Kadane's Algorithm.
13+
14+
Parameters
15+
----------
16+
arr: list[int], the input list of integers
17+
18+
Returns
19+
-------
20+
int: the maximum subarray sum
21+
22+
>>> kadanes_algorithm([-2, 1, -3, 4, -1, 2, 1, -5, 4])
23+
6
24+
>>> kadanes_algorithm([1])
25+
1
26+
>>> kadanes_algorithm([-1, -2, -3])
27+
-1
28+
>>> kadanes_algorithm([5, 4, -1, 7, 8])
29+
23
30+
>>> kadanes_algorithm([0, 0, 0])
31+
0
32+
>>> kadanes_algorithm([-2, -3, 4, -1, -2, 1, 5, -3])
33+
7
34+
"""
35+
if not arr:
36+
raise ValueError("Array cannot be empty")
37+
38+
max_sum = current_sum = arr[0]
39+
40+
for num in arr[1:]:
41+
current_sum = max(num, current_sum + num)
42+
max_sum = max(max_sum, current_sum)
43+
44+
return max_sum
45+
46+
47+
if __name__ == "__main__":
48+
import doctest
49+
50+
doctest.testmod()
51+
52+
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
53+
print(f"Maximum subarray sum: {kadanes_algorithm(arr)}")

0 commit comments

Comments
 (0)