Arrays & Hashing · Pattern 3 of 26

Kadane's algorithm: the best subarray ending here

At each index, the best subarray ending here either extends the best one ending at the previous index or starts fresh. Track that and the best seen so far.

5 variations · 7 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Maximum (or minimum) sum of a contiguous subarray
  • A running total that is worth dropping once it hurts you
  • Circular arrays or products as a twist

The template

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

The variations

  1. 1Best (or worst) subarray ending here

    Extend or restart at every index. The minimum version is the same with min.

  2. 2Circular array

    A wrapping subarray is the total minus a middle subarray. Answer = max(normal Kadane, total − minimum subarray), unless every value is negative.

  3. 3Carry two values

    For products keep the max and the min ending here, because multiplying by a negative swaps them. For "values[i] + values[j] + i − j" keep the best values[i] + i so far.

    Now you solve
  4. 4Reset when the running balance goes negative

    If the tank runs dry at station i, no station between the start and i can work either. Start again at i + 1.

    Worked example Gas Station Medium Read the solution
  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Starting with 0 instead of nums[0]: an all-negative array then returns 0.
  • For products, tracking only the maximum: a negative number turns the minimum into the maximum.
  • For the circular case, forgetting that "total − minimum subarray" is invalid when every number is negative.
Next: The double reversal trick →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.