Kadane's Algorithm
Carry the best run ending here. A negative run only hurts, so drop it and start over.
Decision · step 2 of 10Prefix Sum and Kadane: Kadane on a mixed array
The run so far totals -2, and dragging that along would only hurt. Start over at 1. That is a new best.
What you will see
A running sum bar grows or resets; the best range so far is highlighted.
Cost
| Best | O(n) |
|---|---|
| Average | O(n) |
| Worst | O(n) |
| Space | O(1) |
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.
Screen readers: Each cell is announced as index, value and state; each step's accessibility text states the decision and its effect.
Reduced motion: Swaps and shifts become value crossfades with an outline flash; pointers appear at their destination.
Before this
Taught by the same lesson
Prefix Sum and Kadane covers these too, in the same run.