Skip to content
StackDecode
Array techniquesAnimated

Kadane's Algorithm (Maximum Subarray)

Track the best sum ending at each position; restart when it goes negative.

Time

O(n)

Extra space

O(1)

Use it for

Largest contiguous sum in an array.

How it works

  1. Walk through the array keeping "the best sum of a subarray that ends here".
  2. At each item choose: extend the previous subarray (current + item) or start fresh at this item, whichever is larger.
  3. If the running sum drops below the item itself, the old part was only dragging us down, so restart.
  4. Remember the largest running sum ever seen. That is the answer, found in a single pass.

Watch it run

Loading animation…