- What a contiguous subarray is β and why the naive approach is too slow
- Kadane's algorithm β the O(n) insight that solves this in a single pass
- Why "reset when the running sum goes negative" is the correct local decision
- How to handle all-negative arrays correctly
- How to extend Kadane's algorithm to find the actual subarray bounds
What the maximum-sum subarray problem is
Given an array of integers, find the contiguous subarray (a slice of consecutive elements) whose sum is the largest. A "subarray" must be contiguous β you can't skip elements. So for [1, 2, 3, 4, 5], valid subarrays include [1], [1, 2], [2, 3, 4], [1, 2, 3, 4, 5], and so on. The maximum sum subarray is the entire array, sum 15. For [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum subarray is [4, -1, 2, 1], sum 6.
This is one of the most famous algorithmic problems in computer science, and it appears in dozens of interview questions and practical applications. Stock trading (maximum profit from a series of daily changes), signal processing (find the strongest contiguous burst), and image analysis (find the brightest region) all reduce to variants of this problem. It's also the textbook example for teaching dynamic programming and the "local choice β global optimum" reasoning.
The naive approach β check every possible subarray β is O(nΒ³) if you sum from scratch each time, or O(nΒ²) if you precompute prefix sums. For an array of 10,000 elements, that's 100 million to 10ΒΉΒ² operations. Way too slow for real work. Kadane's algorithm solves this in O(n) β a single pass, two variables, no extra space. It's one of those rare algorithms where the fast solution is also the simpler one, once you see the insight.
The insight: as you scan left to right, keep the sum of "the best subarray ending at the current position." If that running sum ever goes negative, it's dragging you down β any future subarray that includes it would be better off starting fresh. So reset the running sum to 0 and start again at the next element. Meanwhile, track the maximum value the running sum has ever reached. That maximum is your answer. One pass, done.
π‘ In one line: current = max(arr[i], current + arr[i]); best = max(best, current); for each i. Initialize both to arr[0]. The answer is best.
Kadane's algorithm β the O(n) insight
Here's the whole algorithm:
current = arr[0]
best = arr[0]
for i = 1 to n-1:
current = max(arr[i], current + arr[i])
best = max(best, current)
return best
Two variables, two updates per iteration, one pass. The magic is in what current represents: it's the sum of the maximum-sum subarray ending at index i. That's a restricted version of the problem, and it's what makes the DP work. At each step, the best subarray ending at i is either:
- Just
arr[i](start fresh). arr[i]plus the best subarray ending ati-1(extend).
Those are the only two possibilities for a contiguous subarray ending at i. And we choose the better of them. The recurrence current = max(arr[i], current + arr[i]) expresses exactly that decision.
Let's trace it for [-2, 1, -3, 4, -1, 2, 1, -5, 4] (the classic LeetCode example):
| i | arr[i] | current | best | Reason |
|---|---|---|---|---|
| 0 | -2 | -2 | -2 | Initial values |
| 1 | 1 | 1 | 1 | max(1, -2+1=-1) = 1 (fresh start) |
| 2 | -3 | -2 | 1 | max(-3, 1-3=-2) = -2 |
| 3 | 4 | 4 | 4 | max(4, -2+4=2) = 4 (fresh start) |
| 4 | -1 | 3 | 4 | max(-1, 4-1=3) = 3 |
| 5 | 2 | 5 | 5 | max(2, 3+2=5) = 5 |
| 6 | 1 | 6 | 6 | max(1, 5+1=6) = 6 |
| 7 | -5 | 1 | 6 | max(-5, 6-5=1) = 1 |
| 8 | 4 | 5 | 6 | max(4, 1+4=5) = 5 |
The maximum is 6, achieved by the subarray [4, -1, 2, 1] (indices 3 to 6). The trace shows the two key decisions:
- At i=1 (arr=1): the running sum was -2 (bad), so we start fresh at 1.
- At i=3 (arr=4): the running sum was -2 (bad), so we start fresh at 4.
After i=3, the running sum never goes negative again, so we just keep extending: 4 β 3 β 5 β 6. The final answer is the max over all values of current.
π― The core insight: a negative running sum is always a liability β any subarray that includes it would be better off starting after it. So reset to 0 (i.e., start fresh at the next element). This local decision is globally optimal, and it's what makes Kadane's algorithm work.
Complete C Program
Program: find the maximum sum subarray
#include <stdio.h>
/* Function prototype */
long long maxSubarraySum(const int arr[], int n);
int main(void) {
int arr[100];
int n;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
printf("Please enter a valid count between 1 and 100.\n");
return 1;
}
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) return 1;
}
printf("Maximum sum subarray: %lld\n", maxSubarraySum(arr, n));
return 0;
}
/* Kadane's algorithm */
long long maxSubarraySum(const int arr[], int n) {
long long current = arr[0];
long long best = arr[0];
for (int i = 1; i < n; i++) {
long long extended = current + arr[i];
if (arr[i] > extended) current = arr[i];
else current = extended;
if (current > best) best = current;
}
return best;
}
And a version that also reports the start and end indices of the maximum-sum subarray:
Variant: report the subarray bounds
#include <stdio.h>
long long maxSubarrayWithBounds(const int arr[], int n,
int *outStart, int *outEnd) {
long long current = arr[0];
long long best = arr[0];
int curStart = 0;
int bestStart = 0, bestEnd = 0;
for (int i = 1; i < n; i++) {
if (current + arr[i] < arr[i]) {
current = arr[i];
curStart = i;
} else {
current += arr[i];
}
if (current > best) {
best = current;
bestStart = curStart;
bestEnd = i;
}
}
*outStart = bestStart;
*outEnd = bestEnd;
return best;
}
int main(void) {
int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int s, e;
long long sum = maxSubarrayWithBounds(arr, n, &s, &e);
printf("Max sum: %lld\n", sum);
printf("Subarray [%d..%d]: ", s, e);
for (int i = s; i <= e; i++) printf("%d ", arr[i]);
printf("\n");
return 0;
}
The extra tracking is minimal β one variable curStart to remember where the current run started, and two to remember the best. When the running sum can't be improved by extending, we start fresh at i and update curStart = i. Whenever a new best is found, we snapshot the current run's bounds. Result: not just the sum but the exact indices.
And a version that shows each step of the algorithm:
Variant: verbose trace
#include <stdio.h>
long long maxSubarrayVerbose(const int arr[], int n) {
long long current = arr[0], best = arr[0];
printf("i=0, arr[0]=%d: current=%lld, best=%lld\n",
arr[0], current, best);
for (int i = 1; i < n; i++) {
long long extended = current + arr[i];
if (arr[i] > extended) current = arr[i];
else current = extended;
if (current > best) best = current;
printf("i=%d, arr[%d]=%d: extended=%lld, fresh=%d β current=%lld, best=%lld\n",
i, i, arr[i], extended, arr[i], current, best);
}
return best;
}
int main(void) {
int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = 9;
printf("\nFinal answer: %lld\n", maxSubarrayVerbose(arr, n));
return 0;
}
Running this shows every decision: at each step, whether we extend (extended > fresh) or start fresh. It's the clearest way to internalize the algorithm β you can see the running sum dip into negatives, get reset, and grow back up.
Program Output
A typical run with the classic example:
How many elements? 9
Enter 9 integers: -2 1 -3 4 -1 2 1 -5 4
Maximum sum subarray: 6
The maximum-sum subarray is [4, -1, 2, 1] (indices 3 through 6), sum 6. This is the well-known answer for the LeetCode #53 example.
With all positive numbers:
How many elements? 5
Enter 5 integers: 1 2 3 4 5
Maximum sum subarray: 15
When everything is positive, the maximum-sum subarray is the entire array. Sum = 1+2+3+4+5 = 15.
With all negative numbers:
How many elements? 4
Enter 4 integers: -3 -1 -4 -2
Maximum sum subarray: -1
When all values are negative, the best you can do is the single largest element (least negative). Here, -1 is the max. This is why initializing current = arr[0] and best = arr[0] is critical β initializing to 0 would incorrectly return 0 for all-negative arrays (the empty subarray, which is not a valid answer).
A single element:
How many elements? 1
Enter 1 integers: 42
Maximum sum subarray: 42
The loop doesn't execute, and the function returns arr[0] = 42, which is correct β the only subarray is the single element.
And the bounds-reporting variant:
Max sum: 6
Subarray [3..6]: 4 -1 2 1
Not just "the max is 6" but "the max is 6, from indices 3 to 6, values 4, -1, 2, 1." That's the version most real applications want.
And the verbose trace:
i=0, arr[0]=-2: current=-2, best=-2
i=1, arr[1]=1: extended=-1, fresh=1 β current=1, best=1
i=2, arr[2]=-3: extended=-2, fresh=-3 β current=-2, best=1
i=3, arr[3]=4: extended=2, fresh=4 β current=4, best=4
i=4, arr[4]=-1: extended=3, fresh=-1 β current=3, best=4
i=5, arr[5]=2: extended=5, fresh=2 β current=5, best=5
i=6, arr[6]=1: extended=6, fresh=1 β current=6, best=6
i=7, arr[7]=-5: extended=1, fresh=-5 β current=1, best=6
i=8, arr[8]=4: extended=5, fresh=4 β current=5, best=6
Final answer: 6
Every decision is visible. At i=1 and i=3, the extended sum is worse than starting fresh, so we reset. At i=6, we reach the peak of 6. After that, the running sum drops but the best is already recorded. The final answer is 6.
Step-by-Step Explanation
Let's understand the algorithm deeply, then walk through the code.
1. The recurrence
The best subarray ending at index i is max(arr[i], best_ending_at(i-1) + arr[i]). Two choices: start fresh at arr[i], or extend the previous best. Whichever gives a larger sum wins. This is the local decision β and it turns out to be globally correct, in the sense that the global maximum is the maximum over all local bests.
2. Why it works
Suppose the maximum-sum subarray ends at index k. Then its sum is exactly best_ending_at(k) β the best subarray ending at k. And our algorithm computes that correctly, by induction:
- Base case:
best_ending_at(0) = arr[0]. Trivially true (only one subarray ends at index 0). - Inductive step: the best subarray ending at
keither includesarr[k-1]or doesn't. If it does, it must be the best ending atk-1extended byarr[k]. If not, it's justarr[k]. Sobest_ending_at(k) = max(arr[k], best_ending_at(k-1) + arr[k]). This is our recurrence.
By induction, our recurrence computes the correct value at each step. The global maximum is then the maximum over all best_ending_at(k), which is exactly what best = max(best, current) tracks.
3. Tracing [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Already traced in the table above. Key moments:
- After i=1,
current = 1(fresh start at 1, because extending -2 would be -1, worse than 1). - After i=3,
current = 4(fresh start, because extending -2 would be 2, worse than 4). - After i=6,
current = 6(the peak β extending 5 with 1 gives 6). besttracks 6 from i=6 onward.
4. Why initialize to arr[0] and not 0
For all-negative arrays, initializing to 0 would give a wrong answer. For [-3, -1, -4, -2], the maximum-sum subarray is [-1] with sum -1. If best started at 0, we'd never update it, and the answer would incorrectly be 0. Starting at arr[0] correctly returns -1. This is the single most common bug in Kadane's algorithm.
5. The equivalent "reset to 0" form
Many implementations write Kadane's algorithm as:
long long best = arr[0], current = 0;
for (int i = 0; i < n; i++) {
current += arr[i];
if (current > best) best = current;
if (current < 0) current = 0;
}
This is mathematically equivalent to the max-based form: when current + arr[i] < arr[i], it means current < 0, so arr[i] is chosen β equivalent to resetting to 0 and adding arr[i]. Both compute the same current at every step. Use whichever reads clearer to you; the max version is arguably more explicit about the two-way choice.
6. Tracking the subarray bounds
The maxSubarrayWithBounds version adds three variables: curStart (where the current run began), bestStart, bestEnd. Each time we start fresh (because extending is worse), we update curStart = i. Each time we update best, we snapshot curStart and i into bestStart and bestEnd. The bookkeeping is minimal β the algorithm is unchanged.
7. Complexity
O(n) time β one pass, one comparison + one update per iteration. O(1) space β a handful of variables. Optimal. Compare with the naive O(nΒ²) approach (check every subarray's sum): for n=10,000, that's 50 million operations vs. 10,000. The speedup is 5,000Γ. For larger arrays, the gap grows quadratically.
8. Why it's called Kadane's algorithm
The algorithm was published by Jay Kadane in 1984, in a paper about maximum-likelihood estimation for a statistical model. But it was already known as a solution to the maximum subarray problem β some sources credit Ulf Grenander (1977) or Michael Shamos (1978) with earlier versions. Kadane's name stuck because his was the clearest formulation, and because the problem appeared in a widely read textbook (Bentley's "Programming Pearls", 1986) with Kadane's solution as the elegant answer. It's one of the few algorithms known by a person's name outside of academic circles.
9. Relation to other problems
Kadane's algorithm is the gateway to many related problems:
- Maximum product subarray: similar, but requires tracking both max and min (because multiplying by a negative flips the sign).
- Maximum sum circular subarray: Kadane's plus Kadane's on the complemented array (via the "max = total - min" trick).
- Maximum sum subarray with at most k negatives: a harder variant requiring a sliding window with a deque.
- Maximum subarray sum modulo m: requires a different approach (prefix sums plus a balanced tree).
- Maximum subrectangle sum (2D): Kadane's on the column-sum reduction, for each pair of rows.
Each of these builds on the core Kadane insight β track "best ending here" and "best overall" β with a twist. Mastering the basic version gives you the foundation for all of them.
10. Application to stock trading
One of the most common applications: given a series of daily stock prices, find the maximum profit from a single buy-sell pair. Compute the daily changes (price[i] - price[i-1]), then find the maximum-sum subarray of those changes. That's the maximum profit you could have made by buying at the start of the subarray and selling at the end. Kadane's algorithm solves this in O(n), which is faster than the naive O(nΒ²) approach (check every buy-sell pair). The same logic applies to any "maximum contiguous gain" problem, including currencies, commodities, and even energy prices β a classic application of a beautiful algorithm.
π Try this: implement the "maximum sum circular subarray" variant. The trick: the maximum-sum subarray either wraps around (doesn't include the middle) or doesn't wrap. For the non-wrapping case, use Kadane's. For the wrapping case, find the minimum-sum subarray and subtract it from the total. Take the max of the two. But be careful: if all elements are negative, the max is the non-wrapping answer (a single negative element), not the difference of two negatives.
Frequently Asked Questions
1. What does "contiguous" mean here?
It means the subarray must be a run of consecutive elements β no skipping. For [1, 2, 3, 4, 5], [2, 3, 4] is contiguous, but [1, 3, 5] is not (it skips 2 and 4). This distinguishes the problem from the "maximum sum subsequence" problem, where you can pick any elements. For subsequences, the max sum is just the sum of all positive elements β much easier, and Kadane's algorithm doesn't apply. The "contiguous" restriction is what makes the problem interesting.
2. Why does initializing to arr[0] matter?
Because if all elements are negative, the maximum-sum subarray is the single largest (least negative) element. For [-3, -1, -4, -2], the answer is -1. If you initialized best = 0, the algorithm would never find anything better than 0 (since all intermediate sums are negative), and it would incorrectly return 0. Initializing to arr[0] ensures the correct answer for all-negative arrays. This is the single most common bug in Kadane's algorithm implementations.
3. Why reset the running sum to 0 when it goes negative?
Because a negative prefix is a liability β any subarray that includes it would be better off starting after it. Think of it this way: if you're trying to maximize a sum, and your running total is already negative, adding more numbers to it only makes sense if those numbers are large enough to overcome the negative. But if you instead drop the negative prefix entirely and start fresh, you always get a larger sum. So the local optimization "reset to 0" is globally correct β it's the optimal decision at every step.
4. Can the maximum subarray be empty?
In the standard problem, no β you must pick at least one element. If the problem allowed an empty subarray (sum 0), you'd initialize best = 0 and the answer for all-negative arrays would be 0 (the empty subarray). Both interpretations exist in the wild, so read the problem statement carefully. LeetCode's "Maximum Subarray" problem (LeetCode #53) requires a non-empty subarray, which is the standard interpretation β the one our program implements.
5. How does this relate to the maximum product subarray?
The product version is a close relative but requires tracking two variables (max and min) instead of one, because multiplying by a negative flips the sign. In the sum case, a negative running sum is always bad (so reset). In the product case, a large negative product can become a large positive product after the next negative β so you must track both the maximum and the minimum product ending at each position. The two-variable version is what makes the product variant work.
6. Can Kadane's algorithm work on 2D arrays?
Yes β for the maximum-sum subrectangle problem. The idea: for each pair of rows (top, bottom), compute the column-wise sum between those rows (giving a 1D array), then run Kadane's algorithm on that 1D array. The maximum over all pairs is the answer. Complexity is O(rowsΒ² Γ cols) β much better than the naive O(rowsΒ³ Γ colsΒ³) approach, but still slower than the 1D case. This is a classic interview problem and a natural extension of the 1D algorithm.
π‘ Tip: Once this works, try the "best time to buy and sell stock" problem β it's a small variation where you compute the daily changes and run Kadane's algorithm on them. Then try the "best time to buy and sell stock with cooldown" problem β a different structure entirely, but the same underlying idea of tracking local state as you scan. These three problems form a nice triad that teaches you how the same basic algorithm adapts to different constraints.