Skip to content

Commit 77c4540

Browse files
authored
Merge pull request #1 from Tanish-S-K/add-kadane-algorithm
Add Kadane's Algorithm to dp/ folder
2 parents 9372040 + 8129c0e commit 77c4540

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
Kadane's Algorithm implementation in Python.
3+
4+
Finds the maximum sum of a contiguous subarray within a one-dimensional array of numbers.
5+
6+
Source:
7+
https://en.wikipedia.org/wiki/Maximum_subarray_problem
8+
"""
9+
10+
from typing import List, Tuple
11+
12+
13+
def kadane(arr: List[int]) -> Tuple[int, List[int]]:
14+
"""
15+
Returns the maximum sum of a contiguous subarray and the subarray itself.
16+
17+
Parameters
18+
----------
19+
arr : List[int]
20+
List of integers (can be positive, negative, or zero).
21+
22+
Returns
23+
-------
24+
Tuple[int, List[int]]
25+
Maximum subarray sum and the corresponding subarray.
26+
27+
Examples
28+
--------
29+
>>> kadane([-2,1,-3,4,-1,2,1,-5,4])
30+
(6, [4, -1, 2, 1])
31+
32+
>>> kadane([1,2,3,4])
33+
(10, [1, 2, 3, 4])
34+
35+
>>> kadane([-1,-2,-3])
36+
(-1, [-1])
37+
"""
38+
if not arr:
39+
raise ValueError("Input array cannot be empty")
40+
41+
max_current = max_global = arr[0]
42+
start = end = s = 0
43+
44+
for i in range(1, len(arr)):
45+
if arr[i] > max_current + arr[i]:
46+
max_current = arr[i]
47+
s = i
48+
else:
49+
max_current += arr[i]
50+
51+
if max_current > max_global:
52+
max_global = max_current
53+
start = s
54+
end = i
55+
56+
return max_global, arr[start:end+1]
57+
58+
59+
# Doctest runner
60+
if __name__ == "__main__":
61+
import doctest
62+
doctest.testmod()

0 commit comments

Comments
 (0)