Dry run
Start with just the first value -2. The running sum and the best sum both begin at -2.
Problem
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Kadane's Algorithm: At each position, decide whether to extend the current subarray or start fresh. If the current sum becomes negative, reset it — a negative prefix only hurts us.
Examples
[4,-1,2,1] has the largest sum = 6
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
Intuition
Either the best subarray ending at the previous position is worth extending, or it is not. If the running sum would make the new element smaller, start a fresh subarray here; otherwise keep extending. Track the best sum seen along the way.
Brute force → Optimal
Consider every start and end index and sum the subarray with a running total.
Kadane's algorithm: one pass where each step chooses to extend or restart and updates the best sum.
Complexity
Edge cases
- All values negative, e.g. [-3,-1,-4,-2]: the answer is the single largest element, -1.
- A single element: it is the only subarray, so return that element.
Common mistakes
- Initialising best to 0, which is wrong for an all-negative array where the true answer is negative.
- Forgetting to restart the running sum when extending would only make the next element smaller.