Array techniquesAnimated
Kadane's Algorithm (Maximum Subarray)
Track the best sum ending at each position; restart when it goes negative.
Time
O(n)
Extra space
O(1)
Use it for
Largest contiguous sum in an array.
How it works
- Walk through the array keeping "the best sum of a subarray that ends here".
- At each item choose: extend the previous subarray (current + item) or start fresh at this item, whichever is larger.
- If the running sum drops below the item itself, the old part was only dragging us down, so restart.
- Remember the largest running sum ever seen. That is the answer, found in a single pass.
Watch it run
Loading animation…