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.
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
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;
} def max_sub_array(nums):
best_here = best = nums[0]
for x in nums[1:]:
best_here = max(x, best_here + x) # extend or start fresh
best = max(best, best_here)
return best int maxSubArray(vector<int>& nums) {
int bestHere = nums[0], best = nums[0];
for (int i = 1; i < (int)nums.size(); i++) {
bestHere = max(nums[i], bestHere + nums[i]); // extend or start fresh
best = max(best, bestHere);
}
return best;
} function maxSubArray(nums) {
let bestHere = nums[0], best = nums[0];
for (let 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
-
1Best (or worst) subarray ending here
Extend or restart at every index. The minimum version is the same with
min.Now you solve -
2Circular array
A wrapping subarray is the total minus a middle subarray. Answer = max(normal Kadane, total − minimum subarray), unless every value is negative.
-
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] + iso far.Now you solve -
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.
-
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
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.
Lesson done
Next: The double reversal trick →Mark it done once you can write the template from memory and you have solved the worked examples yourself.