Learn / Arrays

Kadane and subarray sums

Walk the array once, keeping the best answer for a subarray that ends exactly here. Each new element either extends that run or starts a fresh one, whichever is better. The overall answer is the best of those.

How to recognise it

  • The largest (or smallest) sum of a contiguous subarray.
  • Values can be negative, so a sliding window cannot decide when to shrink.
  • The answer for a run ending at i depends only on the run ending at i - 1.
  • A product instead of a sum, where a negative number can flip the smallest into the largest.

The idea in one picture

You walk along a road of numbers carrying a bag that holds the sum of the stretch you are on. At each step you ask one question: is my bag helping? If the bag's total is negative, it can only drag the next number down, so you empty it and start a fresh stretch here. Otherwise you add the new number. You write down the best total your bag ever held. That is Kadane's algorithm: one pass, two numbers.

Template

current = nums[0]          # best sum of a subarray ending here
best = nums[0]
for i from 1 to n - 1:
    current = max(nums[i], current + nums[i])
    best = max(best, current)
return best

Why it is correct

Every subarray ends somewhere. For a fixed end i, the best subarray ending there is either nums[i] alone or nums[i] added to the best subarray ending at i - 1. Nothing else can be better, because any other choice for the earlier part has a smaller sum. So current is exactly right at every step, and best takes the best over all ends.

A guided example: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

ivaluecurrentbest
0-2-2-2
111 (start fresh)1
2-3-21
344 (start fresh)4
4-134
5255
6166
7-516
8456

Variations

  • Smallest sum: swap max for min in both lines.
  • Product: keep both the largest and the smallest product ending here, and swap them when the new value is negative.
  • Which subarray: remember where the current run started, and copy it into the answer whenever best improves.

Common mistakes

  • Starting current and best at 0, which returns 0 for an all-negative array that has no empty subarray.
  • Returning current at the end instead of best. current is only the best run ending at the last element.
  • Using a sliding window. With negative values a window cannot tell when to shrink.

Problems

0 of 3 solved

Check yourself

Kadane keeps current, the best sum of a subarray ending at the previous index. What is the best sum ending at index i?

Every value is negative, as in [-3, -1, -2]. What does Kadane return?

For the maximum product, why track the smallest product ending here as well as the largest?

How do you get the smallest subarray sum with Kadane?