Find the stretch of numbers with the biggest sum in one pass: carry a running total, and drop it the moment it goes negative.
▼The problem
LeetCode 53 (Medium). Given an integer array nums, find the contiguous subarray (at least one number) with the largest sum and return that sum.
Example (the LeetCode one): [-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6, the run [4, -1, 2, 1].
The solution
def maxSubArray(nums):
total = best = nums[0]
for x in nums[1:]:
total = max(x, total + x)
best = max(best, total)
return bestTranscript
Maximum Subarray. You get an array of positive and negative numbers. Find the contiguous run with the largest sum, and return that sum.
Here's the example: minus two, one, minus three, four, minus one, two, one, minus five, four. The best run is four, minus one, two, one, for a sum of six.
The simple way tries every start with every end. That's forty-five runs for just nine numbers: about n squared. A million numbers means half a trillion sums. Too slow.
The key idea is Kadane's algorithm. A hiker walks the array once, with a backpack holding the running total. Each number moves the trail up or down. Here, the pack climbs to two, then falls to minus two. A negative pack only drags down what comes next: minus two plus three is just one, but three alone is three. So drop the pack and start fresh. And plant a flag at the highest point so far.
In code, total is the pack and best is the flag, and both start at the first number. For each number after that, total becomes the bigger of the number alone, or total plus the number. Taking the number alone drops the pack. Then best keeps the larger of itself and total. Even if every number is negative, best ends on the largest one.
Let's hike. Minus two: the pack and the flag hold minus two. At one, the pack is negative, so drop it and start fresh: one, a new flag. Minus three brings it to minus two. At four, drop it again: four, a new flag. Minus one, two and one take the pack to three, five, then six, and the flag climbs to six. Minus five drops it to one, and four brings it back to five. The flag stays at six.
Each number is visited once, so the time is O of n. And only two numbers are remembered, so the space is O of one.
Drop the negative pack, keep the highest flag. That's Maximum Subarray.