Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Maximum Subarray

MediumLeetCode 53 ↗

The problem, in one line. Given a list of numbers that may be negative, return the largest sum of any unbroken stretch of at least one number. LeetCode 53.

The tell. “Best contiguous stretch” over a list with negatives. If the best stretch ending at each spot depends only on the best stretch ending at the spot before, one running number is enough.

The wrong first idea

Try every start and every end, and add the stretch up.

for i in range(len(nums)):
    total = 0
    for j in range(i, len(nums)):
        total += nums[j]
        best = max(best, total)

Correct, and it reuses the running total so it is not even n cubed. It is still n times n over two. For 100,000 numbers that is 5,000,050,000 stretches, far too many for a list this size.

The invariant

Walk once. At each number decide: extend the stretch that ended just before, or throw it away and start fresh here. A stretch that has gone negative can only drag the next one down, so you drop it.

nums  -2   1  -3   4  -1   2   1  -5   4
cur   -2   1  -2   4   3   5   6   1   5
best  -2   1   1   4   4   5   6   6   6

The sentence that stays true every step: cur is the best sum of a stretch that ends exactly here. The answer is the largest cur seen, kept in best.

The solution

def max_sub_array(nums):
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)     # extend, or start over at x
        best = max(best, cur)
    return best

print(max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
print(max_sub_array([1]))
print(max_sub_array([-3, -1, -2]))
6
1
-1
func maxSubArray(nums []int) int {
	best, cur := nums[0], nums[0]
	for _, x := range nums[1:] {
		cur = max(x, cur+x) // extend, or start over at x
		best = max(best, cur)
	}
	return best
}

Same three calls print 6, 1, -1.

Complexity

  • Time O(n): one pass, two comparisons per number.
  • Space O(1): cur and best are the only state.

Traps

  • Starting best at 0. The all-negative list [-3, -1, -2] then answers 0, but the stretch must hold at least one number, so the answer is -1.
  • Returning cur instead of best. On [5, -10, 1] the final cur is 1 and the answer is 5.
  • Cutting the stretch at every negative number. [4, -1, 2] sums to 5 through the negative, and cutting there reports 4.

Next in the ladder

Jump Game keeps the same one-number walk, but the number is now how far you could possibly have got, and it only ever grows.