Command Palette

Search for a command to run...

← All patterns

Pattern · Pointers & Windows

Kadane's Algorithm

Scan once, keeping the best sum of a subarray ending here: either extend the previous one or start fresh.

Time O(n) · Space O(1)

Taught in Module 2: Arrays

Think of it like this

Walking with a bag of coins that can hold debts: whenever the bag is worth less than nothing, you drop it and start a new bag.

Clues that point here

  • → Maximum (or minimum) subarray sum
  • → "Contiguous subarray" with the best total
  • → Best profit from one buy and one sell

Not this pattern when

  • ✕ Elements can be skipped (that's a subsequence: DP or greedy instead)
  • ✕ The window must have a fixed length (sliding window)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Kadane's Algorithm · template
int bestEndingHere = arr[0], best = arr[0];
for (int i = 1; i < arr.length; i++) {
    bestEndingHere = Math.max(arr[i], bestEndingHere + arr[i]);  // start fresh or extend
    best = Math.max(best, bestEndingHere);
}
return best;

Common versions

  • Maximum subarray
  • Maximum product subarray (track min and max)
  • Best time to buy and sell stock
  • Maximum circular subarray

Practice problems with this pattern

Related patterns