Blind 75 · Greedy

Maximum Subarray

Medium

Watch the walkthrough (5:36)

Problem

Pick one or more numbers that sit next to each other in nums and add them up. Return the largest total such a pick can have.

Examples

Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6

Example 2:
Input: nums = [1]
Output: 1

Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23

Constraints

1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4

Prerequisites

Greedy arguments — and the habit of asking what would have to be true for the local choice to be safe, before trusting it.

How to think about it

1. Drop a Negative Running Sum, Keep the Best Optimal

Intuition

Every pick of numbers side by side ends at some number, so walk the array once and ask, at each number, for the best pick that ends there. It is this number added to the best pick ending just before it, but only if that pick helps. A run whose sum has gone below 0 only drags down whatever comes after it, so drop it and let the next number start a fresh run from 0. The signal is a negative sum, not a negative number: 2 then -1 still sums to 1, which helps the 4 after it. Keep the best running sum seen beside it, starting at the first number rather than at 0, so an array of only negative numbers returns its largest number. Dropping the run at every negative number is the trap: on [3, -4, 2, -1, 4, -6, 1] it throws the -1 away and finds 4, the 4 alone, where 2, -1, 4 makes 5. Drop the running sum once it goes negative, and remember the best sum seen.

Algorithm

1. Start the best at the first number and the running sum at 0.
2. For each number, add it to the running sum.
3. Compare the running sum with the best, and keep the larger.
4. If the running sum is below 0, set it back to 0.
5. Return the best.

Time & Space

Time O(n): one pass, each number added once. Space O(1): two numbers are kept, the running sum and the best.

2. Kadane: Extend or Restart Optimal

Intuition

At each element there is one question: is the run so far helping? If the total behind you is negative it is dead weight, and starting fresh at this element beats carrying it. That single decision — extend or restart — is Kadane's algorithm, and the running best is recorded separately so a later decline cannot erase an earlier peak.

Algorithm

1. Start both the running total and the best at the first element.
2. For each next element, take the larger of the element alone and the element plus the running total.
3. Update the best with the running total.

Time & Space

Time O(n). Space O(1). The divide-and-conquer version is O(n log n) and worth naming as the follow-up.