Quick reference
Kadane's algorithm finds the maximum sum of a contiguous subarray in O(n) time and O(1) space by walking through the array once and keeping track of the best sum of a subarray that ends at the current index.
The idea in one line:
- The best subarray ending here either extends the best one ending at the previous index, or starts fresh at this number. Whichever sum is bigger wins.
The recurrence:
-
best_ending_here = max(nums[i], best_ending_here + nums[i]) -
The answer is the biggest
best_ending_hereyou ever see.
Cost:
- O(n) time, since it looks at each number once, and O(1) extra space, since it only keeps two running sums.
The Maximum Subarray Problem
The maximum subarray problem asks: given an array of numbers, some of them negative, which run of consecutive numbers has the largest sum?
Say a bakery tracked its profit each day for a week, with losses as negative numbers:
[3, −4, 5, −2, 6, −8, 4]
What's the most it made over any stretch of days in a row? Adding up every day gives 4. Just the best single day gives 6. But days 2 through 4 (counting from 0) give 5 − 2 + 6 = 9, which beats both. That's the answer: the best stretch can include a bad day if the days around it make up for it.
If every number were positive, the answer would just be the sum of the whole array. The negative numbers are what make it interesting. Checking every possible subarray works, but there are about n^2 / 2 of them. Kadane's algorithm finds the best one in a single pass. It's named after Jay Kadane, the statistician who came up with it.
How Kadane's Algorithm Works, Step by Step
Every subarray ends somewhere. So instead of asking "what's the best subarray?", Kadane's asks a smaller question at each index: what's the best subarray that ends right here?
A subarray that ends at index i is either:
-
just
nums[i]on its own (start fresh), or -
a subarray that ends at index i - 1, plus
nums[i](extend). If we're going to extend one, we should extend the best one, which we already worked out at the last step.
So we compare those two sums and keep the bigger one. Starting fresh
wins exactly when the best sum ending at the previous index is
negative, since adding a negative number can only drag
nums[i] down. Then we keep a separate "best so far" for
the overall answer.
Here it is on the bakery's week, [3, −4, 5, −2, 6, −8, 4]:
| Index | Number | Extend (best ending at previous + number) | Start fresh | Best ending here | Best so far |
|---|---|---|---|---|---|
| 0 | 3 | (nothing to extend) | 3 | 3 | 3 |
| 1 | −4 | 3 + (−4) = −1 | −4 | −1 (extend) | 3 |
| 2 | 5 | −1 + 5 = 4 | 5 | 5 (start fresh) | 5 |
| 3 | −2 | 5 + (−2) = 3 | −2 | 3 (extend) | 5 |
| 4 | 6 | 3 + 6 = 9 | 6 | 9 (extend) | 9 |
| 5 | −8 | 9 + (−8) = 1 | −8 | 1 (extend) | 9 |
| 6 | 4 | 1 + 4 = 5 | 4 | 5 (extend) | 9 |
The answer is 9, from indexes 2 through 4: [5, −2, 6]. Notice two things:
- At index 1, the best sum ending there is −1. Extending is still better than starting fresh at −4, but a negative running sum is a burden, so at index 2 we drop it and start over at 5.
- At index 5, a big loss of 8 doesn't force a restart, because the running sum (9) is big enough to absorb it. It just never produces a new best.
Kadane's Algorithm Code
This version needs at least one number and always returns the sum of a non-empty subarray, so for an all-negative array it returns the largest single number (more on that below):
Both running values start at the first number, not at 0. That one detail is what makes the all-negative case come out right.
All-Negative Arrays (and Empty Subarrays)
What's the maximum subarray sum of [−3, −1, −2]? There are two reasonable answers, and the problem statement decides which one you want:
| Version | Answer for [−3, −1, −2] | How to code it |
|---|---|---|
| The subarray must have at least one number (the usual interview version, and the code above) | −1, the largest single number | Start both running values at nums[0] and loop from index 1 |
| An empty subarray is allowed, with a sum of 0 | 0 | Return the larger of 0 and the non-empty answer |
A lot of Kadane's code you'll find online starts the best sum at 0 and resets the running sum to 0 whenever it goes negative. That's the empty-subarray version. It's fine if the problem allows an empty subarray, but if it doesn't, it returns 0 for an all-negative array even though no subarray sums to 0. If you're not sure which one the interviewer wants, ask.
Finding the Start and End Indices
Interviewers often follow up with "which subarray is it?" To answer, track where the current run starts:
- When we start fresh at index i, the current run now starts at i.
- When the running sum beats the best so far, save the current run's start and the current index as the best start and end.
Keep the current start and the best start in separate variables. The current run can restart many times after the best one was found, and those restarts shouldn't move the answer. If several subarrays tie for the largest sum, this version returns the one that ends first (and, of those, the longest).
Why Kadane's Algorithm Is Dynamic Programming
Kadane's algorithm is a small example of dynamic programming:
- Subproblem: the best sum of a subarray that ends at index i.
-
Recurrence: best ending at
i = max(
nums[i], best ending at i - 1 +nums[i]). - Answer: the largest "best ending at i" over all i, since the best subarray has to end somewhere.
You could fill in a table with one entry per index. But each entry only depends on the one right before it, so a single variable is enough. That's the same trick as computing Fibonacci numbers bottom-up with two variables instead of a whole table, and it's why Kadane's needs only O(1) space.
It also looks greedy: it makes one quick decision per number (keep the running sum, or drop it because it's negative) and never goes back. Both views are fair. The greedy-looking rule "drop a negative running sum" is exactly what the recurrence says to do, and the recurrence is the reason it's safe: no subarray ending later could be helped by starting with a negative-sum prefix.
Kadane's Algorithm vs. Brute Force vs. Prefix Sums
| Approach | Time | Extra space | How it works |
|---|---|---|---|
| Brute force, adding up each subarray | O(n³) | O(1) | Try every start and end, and add up the numbers between them |
| Brute force with a running sum | O(n²) | O(1) | For each start, extend the end one step at a time, adding one number per step |
| Divide and conquer | O(n log n) | O(log n) for the call stack | The best subarray is in the left half, in the right half, or crosses the middle |
| Prefix sums with the smallest prefix so far | O(n) | O(n) for a prefix sum array, or O(1) with running values | The best subarray ending at j is the prefix sum through j minus the smallest earlier prefix sum |
| Kadane's algorithm | O(n) | O(1) | Extend the best subarray ending at the previous index, or start fresh |
The prefix sum approach is Kadane's in disguise. Let
prefix[k] be the sum of the first k
numbers. The sum of nums[i] through
nums[j] is prefix[j + 1] - prefix[i], so to
get the best subarray ending at j, subtract the
smallest prefix sum that comes before it. That difference is exactly
Kadane's "best ending here" at every index.
You can't beat O(n) time, since any number you skip could be a huge positive one that changes the answer. For more on counting steps like this, see our big O notation guide.
What about a sliding window? The usual "shrink the window when it breaks the rule" approach relies on a sum that only goes up as the window grows, and negative numbers break that. Kadane's is what you use instead.
Variations: Maximum Product, Circular Arrays, and Stock Prices
Maximum product subarray
Find the contiguous subarray with the largest product. The twist: multiplying by a negative number turns the biggest product into the smallest and the smallest into the biggest. So at each index we track both the largest and the smallest product of a subarray ending there. The new largest is the biggest of three options: the number alone, the old largest times the number, or the old smallest times the number.
For [−2, 3, −4]:
| Index | Number | Options (alone, × old largest, × old smallest) | Largest ending here | Smallest ending here | Best so far |
|---|---|---|---|---|---|
| 0 | −2 | (just the number) | −2 | −2 | −2 |
| 1 | 3 | 3, −6, −6 | 3 | −6 | 3 |
| 2 | −4 | −4, −12, 24 | 24 | −12 | 24 |
The −6 we kept as the smallest product turns into 24 when it meets −4. If we'd only tracked the largest product, we'd have thrown it away. Zeros take care of themselves: a 0 makes the number alone (0) one of the options, which effectively starts a fresh run.
Maximum circular subarray sum
Now suppose the numbers sit in a circle (like slices around a round cake), so a subarray can wrap from the end back to the start. The best subarray either:
- doesn't wrap, so it's the regular Kadane's answer, or
-
wraps around, which means it's everything
except one stretch in the middle. To make what's left as
big as possible, leave out the stretch with the
smallest sum: the total minus the minimum
subarray sum. Kadane's with
minin place ofmaxfinds that.
For [5, −3, 5], the regular answer is 7 (all three numbers), but the total minus the smallest stretch is 7 − (−3) = 10, from the two 5s joined around the end. One catch: if every number is negative, the smallest stretch is the whole circle, and "total minus smallest" gives 0 for an empty subarray. So in that case return the regular answer.
Best time to buy and sell a stock
Our Apple
Stocks question asks for the best profit from buying one share
and selling it at a later time: the largest
prices[j] - prices[i] with i < j.
That's a maximum subarray problem in disguise:
-
Write down how much the price changes from each time to the next:
changes[k] = prices[k + 1] - prices[k]. -
Buying at time i and selling at time
j earns
prices[j] - prices[i], which equalschanges[i] + changes[i + 1] + ... + changes[j - 1], a contiguous run of changes. - Since you have to sell later than you buy, the run can't be empty. So the best profit is the maximum subarray sum of the changes, using the non-empty version of Kadane's on this page. If the price falls the whole time, every change is negative, and it returns the smallest loss, which is what Apple Stocks asks for.
For the prices [10, 7, 5, 8, 11, 9], the changes are [−3, −2, 3, 3, −2]. The best run is 3 + 3 = 6: buy at $5 and sell at $11. The Apple Stocks solution tracks the lowest price so far instead, which is the prefix sum view of the same idea, since each price is the first price plus a running total of the changes.
Common Mistakes and Interview Tips
-
Starting the best sum at 0. That quietly switches to the empty-subarray version, which returns 0 for an all-negative array. Start at the first number unless empty subarrays are allowed, and say which version you're writing.
-
Mixing up subarrays and subsequences. A subarray has to be contiguous. If you can skip numbers, the best sum is just the sum of all the positive numbers (or the largest number, if none are positive). No Kadane's needed.
-
Moving the best start index on every restart. When you return indices, the current run's start and the best run's start are different variables. Only copy one into the other when the running sum sets a new record.
-
Forgetting the smallest product. For the maximum product subarray, a negative number can turn the smallest product into the largest, so you need both.
-
Integer overflow. In Java and C++, a sum of many large numbers can overflow. Use a 64-bit type if the inputs can be big. See integer overflow.
-
Explaining it. Interviewers like hearing the recurrence in words: "the best subarray ending here either extends the best one ending at the previous index or starts fresh." Then mention O(n) time and O(1) space, and why it's dynamic programming.
Practice the stock-price version of this idea in our Apple Stocks question, which walks from the O(n²) brute force to a one-pass solution and handles a price that falls all day.
Maximum Subarray interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
Your first 3 questions are free. Just sign in, no credit card.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake