← Whiteboard questions

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

Input nums = [3, -5, 4, -1, 6, -8, 2]
Output 9
Why the run 4, -1, 6 adds up to 9, and no other run does better.
Input nums = [-4, -2, -7]
Output -2
Why every number is negative, so the best run is the single item -2.
Input nums = [2, 3, 1]
Output 6
Why every number is positive, so the whole list is the best run.

Constraints

Your answer must contain

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 best

Time and memory

O(n) time, because the list is read once. O(1) memory, because only two numbers are kept.

Common mistakes

  • Starting best at 0. When every number is negative, the answer is the largest single number, not 0. Start from the first item.
  • Returning cur at the end. The best run can finish before the last item, so keep best as well.
  • Allowing an empty run. The run needs at least one item, so [-4, -2, -7] gives -2.

Related problems

More Greedy problems
Maximum Subarray: hints, walkthrough and Python solution