Skip to content

Commit ff6a17d

Browse files
authored
Added Kadane's Algorithm for Maximum Subarray Sum
1 parent ff037fc commit ff6a17d

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed

Diff for: data_structures/arrays/maximum_subarray.py

+24-26
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,24 @@
1+
"""
2+
Kadane's Algorithm is an efficient method to find the maximum
3+
sum of a contiguous subarray within a one-dimensional array of
4+
numbers. It maintains two key values as we traverse the array:
5+
the current maximum sum ending at the current index and the
6+
global maximum sum found so far.
7+
"""
8+
9+
# Advantages
10+
"""
11+
- Efficiency: Runs in linear time, `O(n)`.
12+
- Simplicity: Straightforward to implement and understand.
13+
- Versatility: Easily adaptable to related problems.
14+
"""
15+
16+
# Time Complexity
17+
"""
18+
- Time Complexity: `O(n)` - processes each element once.
19+
- Space Complexity: `O(1)` - uses a fixed amount of extra space.
20+
"""
21+
122
"""
223
Find the Maximum Subarray Sum using Kadane's Algorithm.
324
Reference: https://leetcode.com/problems/maximum-subarray/
@@ -13,7 +34,6 @@
1334
Example Input:
1435
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
1536
Output: 6
16-
1737
"""
1838

1939
def max_subarray_sum(nums: list[int]) -> int:
@@ -37,37 +57,15 @@ def max_subarray_sum(nums: list[int]) -> int:
3757
-1
3858
"""
3959
max_current = max_global = nums[0]
40-
60+
4161
for num in nums[1:]:
4262
max_current = max(num, max_current + num)
4363
max_global = max(max_global, max_current)
4464

4565
return max_global
4666

67+
4768
if __name__ == "__main__":
4869
import doctest
4970

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-
"""
71+
doctest.testmod()

0 commit comments

Comments
 (0)