- Kadane's Algorithm is an algorithm that can find the maximum sum subarray given an array of numbers in O(n) time and O(1) space
- Iterating through the array using an integer variable
current, and at each indexi, determines if elements before indexiare "worth" keeping, or if they should be "discarded".
-
best = negative infinity
-
current = 0
-
for num in nums: 3.1. current = Max(current + num, num) 3.2. best = Max(best, current)
-
return best
def maxSubArray(self, nums: List[int]) -> int:
# Initialize our variables using the first element.
current = best = nums[0]
for num in nums[1:]:
# If current is negative, throw it away. Otherwise, keep adding to it.
current = max(num, current + num)
best = max(best, current)
return bestReference:
Practice: