Maximum subarray sum (Kadane)
At each element, one decision: extend the run you are on, or start again from here. Take whichever gives the larger sum, and track the best seen. One pass, two variables, O(n) time and O(1) space.
Overview
The one decision
At element i there are exactly two candidates for the best subarray ending there: the previous best-ending-here extended by values[i], or values[i] alone. Take the larger. Then the global answer is the largest of those per-element bests.
That is dynamic programming with the table collapsed to a single variable, because each step only needs the one before it. Saying that out loud is worth more than the code.
Step through it
What to watch
- The lighter band is the current run; the solid one is the best so far.
- A run restarts whenever carrying the previous sum would hurt.
- The best is only updated — never reduced.
Say this out loud
"Kadane. At each element I either extend the current run or start fresh from that element, whichever is bigger, and I keep the best I've seen. O(n) time, O(1) space - and I initialise from the first element, not zero, so all-negative input works."