Kadane's algorithm
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Kadane's algorithm finds the best stretch of consecutive items, the one with the biggest total, in a single pass. At each step it asks: is my running bag worth carrying, or should I start fresh here? It turns a slow nested search into one quick walk.
Practical use cases
- Web app: Best run of days for a shop. A shop dashboard shows daily profit, some days negative after ad spend. The owner asks which consecutive days gave the highest combined profit. Checking every start and end pair is slow, but one pass that restarts after a losing stretch finds the best period immediately.
- Web app: Peak performance window in an analytics chart. A fitness app charts daily steps minus the daily goal, so days below the goal are negative. It wants to highlight the stretch of days that beat the goal by the most in total. Tracking the best total ending today and the best seen so far finds that stretch without checking every pair of days.
- System: Stock and signal analysis. Trading tools look for the best buy and sell window in price changes. Signal and genome software search long data streams for the strongest stretch. All use this same walk-and-restart idea, so even years of prices can be scanned in a single quick pass.
The story: Raju's Best Streak
Raju kept a diary of his chai stall: profit on good days, loss on bad days. Some days he earned, some days the rain ruined everything. At month end Mrs. Sharma, who loved puzzles, asked, "Which run of consecutive days made you the most money?"
Raju tried every start day and every end day. For 30 days that was hundreds of additions. He was exhausted and the answer still came late.
Mira had a cleverer idea. "Walk through the diary once. Keep a running streak. At every new day ask just one question: is my old streak helping me or hurting me? If the streak so far is positive, carry it along. If it is a loss, throw it away and start a fresh streak from today."
While walking, she also remembered the biggest streak she had ever seen. One pass, two numbers in her head, and the answer popped out. That walk is called Kadane's algorithm, the neat way to find the maximum-sum subarray.
How to spot this problem, and where you need it
You need the best consecutive stretch in a list of positive and negative numbers, and trying all start and end pairs is far too slow for real data.
Signs you need it
- The problem says maximum sum subarray, best consecutive period, strongest streak, or most profitable window.
- The numbers include negatives, such as losses, drops or penalties, so the answer is not simply the whole list.
- You have two nested loops testing every start and every end, and larger inputs time out.
Where to use it in a project
- Business dashboards finding the best or worst consecutive period for profit, traffic or signups.
- Finance, fitness and sensor charts highlighting the strongest streak in a timeline of ups and downs.
The solution
Walk through once with two numbers: the best total of a stretch ending here, and the best total seen so far. At each item, either extend the previous stretch by adding this item, or start fresh with just this item, whichever is bigger. Update the best seen so far. When the walk ends, the best total seen is the answer, and you can note start and end positions as you go.
Payoff: Before: checking every start and end pair, millions of sums for 3,000 days. After: a single pass of 3,000 steps.
Explain it like I am 8
You are collecting coins and stepping on bad-luck tiles that take coins away. If your bag is in debt, you would happily forget the old bag and start a new bag at the next step. You always remember the fattest bag you ever had.
How it works, step by step
- Keep two numbers:
cur(best streak that ends here) andbest(best streak seen anywhere). - Start both with the first element.
- For each next item x:
cur = max(x, cur + x). Either extend the streak or restart at x. - Update
best = max(best, cur). - After the last item,
bestis the answer. Starting with the first element (not 0) keeps it correct even when all numbers are negative.
The code in four languages
PHP
<?php
// Kadane: best total of any run of consecutive days
function maxStreak(array $profit): int {
$cur = $profit[0]; // best streak ending at day 0
$best = $profit[0];
for ($i = 1; $i < count($profit); $i++) {
$cur = max($profit[$i], $cur + $profit[$i]); // extend or restart
$best = max($best, $cur);
}
return $best;
}
echo maxStreak([-2, 1, -3, 4, -1, 2, 1, -5, 4]) . PHP_EOL; // 6 (4, -1, 2, 1)
echo maxStreak([-5, -2, -9]) . PHP_EOL; // -2 (all losses: least bad day)JavaScript
// Kadane: best total of any run of consecutive days
function maxStreak(profit) {
let cur = profit[0]; // best streak ending at day 0
let best = profit[0];
for (let i = 1; i < profit.length; i++) {
cur = Math.max(profit[i], cur + profit[i]); // extend or restart
best = Math.max(best, cur);
}
return best;
}
console.log(maxStreak([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6 (4, -1, 2, 1)
console.log(maxStreak([-5, -2, -9])); // -2 (all losses: least bad day)Java
public class Main {
// Kadane: best total of any run of consecutive days
static int maxStreak(int[] profit) {
int cur = profit[0]; // best streak ending at day 0
int best = profit[0];
for (int i = 1; i < profit.length; i++) {
cur = Math.max(profit[i], cur + profit[i]); // extend or restart
best = Math.max(best, cur);
}
return best;
}
public static void main(String[] args) {
System.out.println(maxStreak(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4})); // 6 (4, -1, 2, 1)
System.out.println(maxStreak(new int[]{-5, -2, -9})); // -2 (all losses: least bad day)
}
}Go
package main
import "fmt"
// maxStreak is Kadane: best total of any run of consecutive days.
func maxStreak(profit []int) int {
cur := profit[0] // best streak ending at day 0
best := profit[0]
for i := 1; i < len(profit); i++ {
cur = max(profit[i], cur+profit[i]) // extend or restart
best = max(best, cur)
}
return best
}
func main() {
fmt.Println(maxStreak([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4})) // 6 (4, -1, 2, 1)
fmt.Println(maxStreak([]int{-5, -2, -9})) // -2 (all losses: least bad day)
}Time: O(n) · Extra space: O(1). One pass and two variables. Trying every start and end would cost O(n²) or worse.
Watch out for
- Starting
bestat 0. If every number is negative, the true answer is negative (the least bad day), not 0. - Resetting the streak to 0 instead of to the current element, which breaks the all-negative case.
- Confusing
cur(streak that ends here) withbest(best anywhere). You need both.
Quick check
- At a new day x, what does Kadane decide?
- Sort the days
- Extend the streak or restart at x
- Always add x
- What is the answer for [-5, -2, -9]?
- 0
- -2
- -16
- How many passes over the array does Kadane need?
- One
- Two
- As many as there are items