Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Dynamic Programming

The Best Streak.

Watch the explainer

Don't memorize Kadane’s algorithm — watch the best streak emerge. Sweep the array once keeping a running sum. The moment that sum turns negative, throw it away and start fresh — a negative head start can only drag down whatever comes next. Track the best total you have seen, and that is the maximum-sum subarray, in a single O(n) pass.

maximum subarray · running sum · restart · O(n)
CURRENT SUM

The best subarray sum ending exactly at the current index.

RESTART

If current sum ≤ 0, drop it and begin again at this element.

BEST SUM

The largest current sum seen anywhere — the answer.

ONE PASS

Each element seen once, O(n) time, O(1) space.

kadane.sim — maximum-sum subarray
Ready

An array with negatives. Press Step to sweep left to right. The purple window is the current run; the green outline is the best run found so far.

0
Current sum
—
Best sum

A greedy decision, made local

The brute force tries every start and every end — O(n²) subarrays, or O(n³) if you re-add each one. Kadane collapses that into a single question asked at every index: what is the best subarray that ends right here? It is either this element alone, or this element added to the best subarray ending just before it — whichever is larger. If the running sum ever goes non-positive, "this element alone" wins and the window restarts. Keep the maximum of those answers and you are done.

01

Extend or restart

At each element, set cur = max(A[i], cur + A[i]). A negative running sum is dropped in favor of starting fresh.

02

Track the best

Set best = max(best, cur) every step. The best is the answer, wherever it occurred.

03

Why restart works

A negative prefix can only reduce any subarray it is glued to, so discarding it is never worse — the key insight that makes it correct.

04

All-negative case

Initialize best to −∞ and take the element itself on restart, so the answer is the largest single number.

Time
O(n)
Space
O(1)
Brute force
O(n²)
Type
DP

Kadane is the classic “aha” dynamic program: the subproblem is “best subarray ending at i”, and the recurrence reuses the answer for i−1. The same idea extends to the maximum-product subarray (track both max and min because a negative flips them) and to 2-D via a maximum-sum-rectangle reduction.

The picture: what gets thrown away

iAcur -2-20111-3-22443-134255166-517458 best run: 4 − 1 + 2 + 1 = 6 thrown away: sum ≤ 0
The page’s test array, with the running sum cur under each element. Indices 0–2 never help: each time the running sum is ≤ 0 it is dropped. From index 3 the run 4, −1, 2, 1 builds to 6, and nothing after it beats that.

Worked example, step by step

Take A = [-2, 1, -3, 4, -1, 2, 1, -5, 4]. At each index ask one question: is the run so far worth keeping? If cur ≤ 0, restart at this element; otherwise extend. Then compare against best.

iA[i]DecisioncurbestRun
0−2start−2−2[0..0]
11restart (cur was −2)11[1..1]
2−3extend−21[1..2]
34restart (cur was −2)44[3..3]
4−1extend34[3..4]
52extend55[3..5]
61extend66[3..6]
7−5extend16[3..7]
84extend56[3..8]

Two details the trace makes visible. First, the −1 at index 4 is kept: the run was at 4, so 4 − 1 = 3 is still positive and still worth carrying into the 2 and the 1 that follow. Kadane never drops a negative element just for being negative; it drops a negative running sum. Second, after index 6 the run keeps going (1, then 5) but never passes 6, so best remembers the peak while cur moves on. The answer is 6, from indices 3 to 6. A brute force would have checked all 45 subarrays of this 9-element array to find the same thing.

All negative. Run the same loop on [-3, -1, -2]. It starts with cur = best = −3. At −1, restarting beats extending (−1 against −4), so cur = −1 and best = −1. At −2, extending gives −3 and restarting gives −2, so cur = −2, but best stays −1. The answer is −1, the single largest element, and that is right: when every number hurts, the best non-empty subarray is the one that hurts least. This is the input that exposes the best = 0 bug below.

Wrapping around. In the circular version the best run may leave the right end and come back in on the left. Take [5, -3, 5]. Plain Kadane gives 7, the whole array. But the wrapped run 5, 5 skips the −3 and sums to 10. The trick is that a wrapped run is everything except one contiguous middle piece, so its best value is the total minus the minimum subarray: 7 − (−3) = 10, and the answer is max(7, 10) = 10. The guard matters on [-3, -1, -2]. There the minimum subarray is the whole array (−6), the total is also −6, and total − min is 0, which is the empty run. When every element is negative, return the plain Kadane answer, −1.

Complexity and trade-offs

CaseTimeSpaceWhy
KadaneO(n)O(1)One pass, two variables. Each element is read once.
Brute force, re-summingO(n³)O(1)Every start × every end × adding up the slice.
Brute force, running totalO(n²)O(1)Every start, extend the end while keeping a sum.
Prefix sumsO(n)O(n) or O(1)Max of P[j] − min(P[i]); the same idea seen from the other side.
Divide and conquerO(n log n)O(log n)Best of left half, right half, and the best run crossing the middle.

Linear time is optimal: any algorithm must look at every element, because one unseen huge value could be the whole answer. The divide-and-conquer version is slower but splits cleanly across machines, and its segment-tree form answers “maximum subarray in A[l..r]” for many ranges, which plain Kadane cannot.

Common mistakes

  • Starting best at 0

    With best = 0, the all-negative array [-1, -2, -3] returns 0, which is the empty subarray. Most problem statements require at least one element, so the answer is −1. Start best at A[0] (or −∞) and start cur at the first element.

  • Resetting cur to 0 instead of to the element

    Writing cur = max(0, cur + x) is the “empty subarray allowed” variant. Mixed with a best that starts at −∞, it quietly gives wrong answers on all-negative input. Pick one convention: cur = max(x, cur + x) for non-empty.

  • Updating best before cur

    Compare best against the new cur. Updating best first means you check the run that ended at i − 1, and the last element can never be part of the answer.

  • Losing the indices

    If you need the subarray itself, record the start when you restart and copy both start and end into the answer only when best improves. Recording the end on every step returns the end of the current run, not the best one.

  • Applying it to products

    For the maximum product subarray, a negative × a negative flips the sign, so the smallest run so far can become the largest. Track both the running max and min, and swap them on a negative.

Where this shows up

  • Interviews

    “Maximum subarray” (LeetCode 53) is one of the most asked array questions, and its follow-ups are standard: return the indices, the circular version (the larger of Kadane and the total minus the minimum subarray, unless every element is negative), and the maximum product version.

  • Finance and metrics

    The best window to have held a stock is Kadane over daily price changes. The same pass finds the longest profitable stretch in any series of gains and losses, such as revenue deltas or error-budget burn.

  • Signals and genomics

    Finding the strongest burst in a noisy signal, or the highest-scoring segment of a DNA sequence when each base is scored + or −, are both a maximum-sum segment problem.

  • 2-D and beyond

    The maximum-sum rectangle in a matrix fixes a pair of rows, collapses the columns between them into one array, and runs Kadane on it, for O(rows² · cols) in total.

SOLVE IT YOURSELF

Solve it: maximum subarray

This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement max_subarray(nums): return the largest sum of any contiguous subarray (at least one element). Kadane’s trick is one pass — carry the best sum ending at the current position and track the best seen overall. O(n) time, O(1) space.

HINTS — 4 IDEAS
  1. Keep best_here = the largest sum of a subarray that ends at the current element.
  2. At each element x: either extend the previous run or start fresh at x — best_here = max(x, best_here + x).
  3. Keep a separate best = the largest best_here seen so far.
  4. Start both at nums[0] and scan from index 1, so all-negative arrays return their largest single element.
CPython · WebAssembly

Check yourself

1 · What does Kadane do when the running current sum drops to zero or below?

A non-positive prefix can only hurt what follows, so it is dropped and the current window restarts fresh.

2 · What is the time complexity of Kadane’s algorithm?

A single pass touching each element once with constant work — linear time, constant space.

3 · The subproblem Kadane solves at each index is:

That local answer, maximized over all indices, is the global maximum subarray — a clean dynamic program.

Questions

How do you also return the subarray, not just the sum?

Track the start index whenever you restart the window, and the end index whenever you update the best. When best improves, record the current start and the current index as the best range.

What about maximum product subarray?

Products behave differently because a negative times a negative is positive, so you track both the running maximum and minimum product at each step and swap them when you hit a negative number. Same one-pass shape, two variables.

Why is this considered dynamic programming?

Because the answer at index i is built directly from the answer at i−1 (extend it or restart), which is the essence of DP: optimal substructure plus reuse of a previously computed result.

One sweep, one running sum, the best streak wins.

Drop the negatives, keep the best. The maximum-subarray classic in O(n).

▶  Watch it explained

Kadane's Algorithm: The Best Stretch in One Pass

Finished this one? 0 / 99 Algorithms done
NextThe Fewest Coins: Coin Change Next on the “DP along one axis” ladder · rung 2 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms