Maximum Subarray
Find the best sum of a consecutive run
DSA, Medium, Greedy
Which structure or algorithm, and what does it cost.
A list nums holds whole numbers, and some are negative. Pick a run of one or more neighbouring items, with no gaps. Return the largest sum that any such run can have. The run needs at least one item, so a list of only negative numbers gives its largest single value.
Examples
Constraints
- 1 <= length of
nums<= 200,000. - Each number is a whole number between -9,000 and 9,000.
Your answer must contain
- The simple method and why it is too slow; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time and O(1) extra memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Fix an end item and think about the runs that finish there. How do they relate to the runs that finish one item earlier?
Hint 2 the approach
For each item, track the best sum of a run that ends there, plus the best answer seen so far. Ask how the first depends on the item before.
Hint 3 the key step
Look at the best run ending at the previous item. When is it worth carrying into this one, and when is it not?
Walkthrough
Full walkthrough brute force to best
Brute force
Try every start and every end. Grow the end one item at a time and keep a running sum, so each pair costs O(1). That is about n * n / 2 pairs, so O(n^2) time and O(1) extra memory. With 200,000 items that is about 20 billion pairs, too slow.
Best method
Walk the list once. Keep cur, the best sum of a run that ends at the current item, and best, the largest cur seen so far. At each item, cur is the item alone or the item added to the old cur, whichever is larger. Dropping a run with a negative sum is safe. Suppose the best run had a front part with a negative sum. Cutting that part off would give a larger sum, which is a contradiction. So the best run never starts with a negative front part, and starting fresh at that point loses nothing.
Hand trace
Run on [3, -5, 4, -1, 6, -8, 2]. Start with cur 3 and best 3. Item -5: cur is the larger of -5 and 3 + -5, which is -2, and best stays 3. Item 4: the old run is a burden, so cur restarts at 4 and best is 4. Item -1: cur is 3. Item 6: cur is 9 and best is 9. Item -8: cur is 1. Item 2: cur is 3. The answer is 9, the run 4, -1, 6.
Code
def max_subarray(nums):
best = cur = nums[0] # best run so far, best run ending here
for x in nums[1:]:
cur = max(x, cur + x) # extend the old run or start fresh
best = max(best, cur)
return bestTime and memory
O(n) time, because the list is read once. O(1) memory, because only two numbers are kept.
Common mistakes
- Starting
bestat 0. When every number is negative, the answer is the largest single number, not 0. Start from the first item. - Returning
curat the end. The best run can finish before the last item, so keepbestas well. - Allowing an empty run. The run needs at least one item, so [-4, -2, -7] gives -2.