Skip to content

Commit 8129c0e

Browse files
authored
Add Kadane's Algorithm to dp/ folder
Added Kadane's Algorithm to the dp/ folder to find the maximum sum of a contiguous subarray. The implementation follows TheAlgorithms/Python guidelines: - Returns both maximum sum and the corresponding subarray. - Includes type hints, docstring, and doctests. - References Wikipedia for source: https://en.wikipedia.org/wiki/Maximum_subarray_problem Example: >>> kadane([-2,1,-3,4,-1,2,1,-5,4]) (6, [4, -1, 2, 1])
1 parent 9372040 commit 8129c0e

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

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)