Skip to content

Commit 2b64e18

Browse files
authored
Adding kadane's algorithm to dp/ folder
kadane's algorithm is not present in dynamic_programming folder so adding it.
1 parent 788d95b commit 2b64e18

File tree

1 file changed

+61
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)