Arrays · Core Array Techniques

Kadane's Algorithm

Tracking the best subarray ending at each position to find a maximum-sum contiguous subarray in one pass.

  • 4 min read
  • 14 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach
  3. Where you'll see it
  4. Which tool for which job?
  5. Common mistakes
  6. Check yourself
  7. Key takeaways
  8. Quick revise
  9. Practice

Description

Kadane's algorithm finds the contiguous subarray with the largest sum in one pass. At each element it asks one question: is it better to extend the run that ends just before me, or to start fresh here? Then it keeps the best answer seen so far. It's the smallest dynamic-programming problem you'll meet. The same scan finds the best stretch in any series, such as the biggest gain in a price history or the worst run of slow responses.

We'll go from simple to more technical:

  1. The pattern: the best sum ending here, and the best so far.
  2. Where the same scan shows up in production time series.
  3. The edge cases: all-negative arrays, empty input, sum versus the subarray itself.
  4. Where it stops: two dimensions, and other variants.

The approach

Checking every subarray works, but it's O(n^2): each start index adds up a growing range again. Kadane's keeps two numbers instead. bestEndingHere is the best sum of a run that ends at the current element. best is the best sum seen anywhere. At each element, either add it to the run or start a new run with it, whichever is larger. A run whose sum has gone negative can only drag the next element down, so that's when it restarts.

For [3, -5, 4, -1, 2, -6, 1]:

ElementExtend or restart?Best ending hereBest so far
3start33
-5extend: 3 - 5 = -2-23
4restart: 4 beats -2 + 444
-1extend: 4 - 1 = 334
2extend: 3 + 2 = 555
-6extend: 5 - 6 = -1-15
1restart: 1 beats -1 + 115

The answer is 5, from [4, -1, 2].

Java

int bestEndingHere = nums[0];
int best = nums[0];
for (int i = 1; i < nums.length; i++) {
    bestEndingHere = Math.max(nums[i], bestEndingHere + nums[i]);
    best = Math.max(best, bestEndingHere);
}

Python

best_ending_here = best = nums[0]
for x in nums[1:]:
    best_ending_here = max(x, best_ending_here + x)
    best = max(best, best_ending_here)

This is dynamic programming in its smallest form. The best run ending at index i depends only on the best run ending at index i - 1. So the whole table shrinks to one variable.

Where you'll see it

"Find the best or worst stretch" comes up with any time series. The largest drop in an account balance is one. Another is the worst stretch of slow responses, measured as the time window with the most total latency over the target. Both are the same scan.

Which tool for which job?

You needUse
The largest contiguous sumKadane's: extend or restart
The smallest contiguous sumKadane's with min
The largest sum when the array wraps aroundmax(Kadane, total - smallest sum)
The largest contiguous producttrack the max and the min ending here
The best buy-then-sell profitKadane's on day-to-day differences
The largest-sum rectangle in a matrixfix two rows, collapse, run Kadane's - O(rows^2 * cols)

Common mistakes

MistakeWhat happensDo this instead
Starting best at 0an all-negative array reports 0start from nums[0]
Starting from nums[0] with no empty checkan exception stands in for a decisionreject empty input, or return an empty optional
Returning the sum when the subarray was asked forthe wrong answer to the questiontrack where the current run started
Updating best before bestEndingHerethe newest element is ignoredupdate the run first, then the best
Expecting it to work on productssign flips are missedtrack the max and the min

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. Kadane's starts with best = 0 instead of nums[0]. What breaks, and on which inputs?

Show answer

An all-negative array returns 0, but no subarray of it sums to 0. The right answer is its largest single element, such as -1 for [-3, -1, -4]. Starting from 0 makes every real answer look worse than a made-up one.

2. Why is Kadane's called the simplest dynamic-programming problem?

Show answer

The best run ending at index i depends only on the best run ending at index i - 1, plus nums[i]. Only the previous answer is ever needed again, so the DP table shrinks to one running variable.

3. A solution returns the right maximum sum. Now it must return the subarray itself. Is that the same work?

Show answer

No. The sum needs two running numbers. The subarray also needs the start of the current run, updated whenever the run restarts, and the start and end of the best run, saved whenever a new best appears. A correct sum doesn't prove the index bookkeeping is correct.

Key takeaways

  • At each element, extend the current run or restart from the element, whichever is larger. That's the whole O(n) idea.
  • Start both values at nums[0], not 0, or an all-negative array returns 0.
  • The best run ending at i depends only on the best run ending at i - 1, so the DP table is one variable.
  • Returning the subarray needs extra index tracking beyond the sum.
  • The 2D version (the best rectangle) runs Kadane's once per pair of rows: O(rows^2 * cols).

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
Largest contiguous sumextend or restart
Smallest contiguous sumthe same with min
Circularmax(Kadane, total - min), unless all negative
Largest producttrack max and min ending here
Best single tradeKadane's on differences
Largest rectangletwo rows fixed, collapse, Kadane's

Snippets worth knowing by heart

Java

int cur = nums[0], best = nums[0], start = 0, bestStart = 0, bestEnd = 0;
for (int i = 1; i < nums.length; i++) {
    if (cur + nums[i] < nums[i]) { cur = nums[i]; start = i; }   // restart
    else cur += nums[i];                                         // extend
    if (cur > best) { best = cur; bestStart = start; bestEnd = i; }
}

Python

cur = best = nums[0]
for x in nums[1:]:
    cur = max(x, cur + x)      # extend or restart
    best = max(best, cur)

The traps

  • best = 0: an all-negative array reports 0. Start from nums[0].
  • Empty input with no decision: an exception stands in for an answer. Reject it, or return an empty optional.
  • The sum when the subarray was asked for: you answer the wrong question. Track where the current run started.
  • Products without the minimum: a sign flip turns the smallest product into the largest. Track the max and the min.
  • Circular total - min on all negatives: it returns 0, the empty subarray. Return the max element instead.

Staff-level points, one line each

  • It's a DP: best ending at i = max(nums[i], best ending at i - 1 + nums[i]).
  • Ties: > gave [0..0] and >= gave [0..2] on [3, -3, 3].
  • Circular on [-3, -2, -5]: total - min said 0; the answer is -2.
  • Products: max only gave 6, max and min gave 48 on [2, 3, -2, 4, -1].
  • Stock profit = Kadane's on differences (98 = brute force).
  • 2D: O(rows^2 * cols), smaller side squared.

Say it in an interview

  • "At each element I either extend the best run ending before it or start fresh."
  • "I start from the first element so all-negative arrays work."
  • "It's the simplest DP: one state, only the previous value needed."
  • "For the circular version I subtract the smallest subarray from the total."

Practice

This skill comes with 14 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Kadane's Algorithm free

Maximum Subarray

MediumProCoding problemJava · Python

Pick a run of one or more consecutive numbers from nums so that their total is as large as possible, and return that total.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Maximum Subarray, Reconstructed

MediumProCoding problemJava · Python

Given an array of integers, find the contiguous subarray with the largest sum, and print the actual subarray (the elements themselves, space-separated) rather than just its sum. If multiple subarrays share the maximum sum, print the leftmost one.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Kadane's Algorithm free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime