Skip to content

Commit 02e6890

Browse files
authored
Added Kadane's Algorithm for Maximum Subarray Sum
1 parent fcf82a1 commit 02e6890

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Diff for: data_structures/arrays/Maximum Subarray.py

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""
2+
Find the Maximum Subarray Sum using Kadane's Algorithm.
3+
Reference: https://leetcode.com/problems/maximum-subarray/
4+
5+
Python doctest can be run with the following command:
6+
python -m doctest -v maximum_subarray.py
7+
8+
Given an integer array nums, this function returns
9+
the maximum sum of a contiguous subarray.
10+
11+
A subarray is a contiguous part of an array.
12+
13+
Example Input:
14+
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
15+
Output: 6
16+
17+
"""
18+
19+
def max_subarray_sum(nums: list[int]) -> int:
20+
"""
21+
Find the maximum subarray sum using Kadane's Algorithm.
22+
23+
Args:
24+
nums (list[int]): The input array of integers.
25+
26+
Returns:
27+
int: The maximum subarray sum.
28+
29+
Examples:
30+
>>> max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])
31+
6
32+
>>> max_subarray_sum([1])
33+
1
34+
>>> max_subarray_sum([5, 4, -1, 7, 8])
35+
23
36+
>>> max_subarray_sum([-1, -2, -3, -4])
37+
-1
38+
"""
39+
max_current = max_global = nums[0]
40+
41+
for num in nums[1:]:
42+
max_current = max(num, max_current + num)
43+
max_global = max(max_global, max_current)
44+
45+
return max_global
46+
47+
if __name__ == "__main__":
48+
import doctest
49+
50+
doctest.testmod()
51+
52+
53+
# Kadane's Algorithm
54+
55+
"""
56+
Kadane's Algorithm is an efficient method to find the maximum
57+
sum of a contiguous subarray within a one-dimensional array of
58+
numbers. It maintains two key values as we traverse the array:
59+
the current maximum sum ending at the current index and the
60+
global maximum sum found so far.
61+
"""
62+
# Advantages
63+
"""
64+
- Efficiency**: Runs in linear time, `O(n)`.
65+
- Simplicity**: Straightforward to implement and understand.
66+
- Versatility**: Easily adaptable to related problems.
67+
"""
68+
69+
### Time Complexity
70+
"""
71+
- Time Complexity**: `O(n)` - processes each element once.
72+
- Space Complexity**: `O(1)` - uses a fixed amount of extra space.
73+
"""

0 commit comments

Comments
 (0)