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
+
1
22
"""
2
23
Find the Maximum Subarray Sum using Kadane's Algorithm.
3
24
Reference: https://leetcode.com/problems/maximum-subarray/
13
34
Example Input:
14
35
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
15
36
Output: 6
16
-
17
37
"""
18
38
19
39
def max_subarray_sum (nums : list [int ]) -> int :
@@ -37,37 +57,15 @@ def max_subarray_sum(nums: list[int]) -> int:
37
57
-1
38
58
"""
39
59
max_current = max_global = nums [0 ]
40
-
60
+
41
61
for num in nums [1 :]:
42
62
max_current = max (num , max_current + num )
43
63
max_global = max (max_global , max_current )
44
64
45
65
return max_global
46
66
67
+
47
68
if __name__ == "__main__" :
48
69
import doctest
49
70
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