Maximum Subarray (Kadane's)
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
- 1 <= nums.length <= 10⁵
- -10⁴ <= nums[i] <= 10⁴
nums = [-2,1,-3,4,-1,2,1,-5,4]6nums = [1]1nums = [5,4,-1,7,8]23nums = [-3,-5,-1]-1Finding the maximum subarray sum means identifying a contiguous chunk of numbers within an array that adds up to the highest possible total. The challenge is that negative numbers can "reset" our progress, making it difficult to decide where a subarray should start and end.
The most direct way to solve this is to check every possible subarray. We pick a starting index, then scan to the right to calculate every possible ending index, keeping track of the best sum we find.
max_sum = nums[0]
for i in range(len(nums)):
current_sum = 0
for j in range(i, len(nums)):
current_sum += nums[j]
max_sum = max(max_sum, current_sum)
return max_sumThe brute force is slow because it recalculates every window from scratch. The core insight is that a negative sum is dead weight. If our current total is negative, adding it to the next number will only make that number smaller. We are always better off dumping the negative debt and starting fresh.
Instead of checking every window, we walk through the array once. At every step, we decide: "Should I continue the current streak, or should I start a brand new streak at this number?" If the previous streak is negative, it's "debt" — we are always better off resetting the count to the current number.
current_streak = 0
max_result = nums[0]
for x in nums:
# If the current streak is negative, it helps no one. Start fresh at x.
current_streak = max(x, current_streak + x)
max_result = max(max_result, current_streak)
return max_result