curSum after each index
public int maxSubArray(int[] nums) { int maxSub = nums[0]; int curSum = 0; for (int n : nums) { if (curSum < 0) { // a negative prefix only hurts curSum = 0; } curSum += n; maxSub = Math.max(maxSub, curSum); } return maxSub;}
- i
- —
- n
- —
- curSum
- 0
- maxSub
- —
- window
- —
Why it works
- Brute force sums every subarray: fix a start, extend the end, track the best. O(n²) with a running sum, O(n³) without.
- A negative prefix never helps. If the run ending just before
nsums below zero, any subarray that keeps it is beaten by the same subarray without it. So resetcurSumto 0 and start fresh atn. - Invariant: after each index,
curSumis the best sum of a subarray that ends exactly there. The answer ends somewhere, so the max over all indices is the answer. One pass, two numbers: O(n) time, O(1) space. - Pitfall: start
maxSubatnums[0], not 0. With all negatives,[-3,-1,-2], the answer is-1: the subarray must be non-empty. - Related: this is DP with the table squeezed to one cell:
bestEnd[i] = Math.max(nums[i], bestEnd[i-1] + nums[i]). The same reset idea drives Gas Station (134), and the product version, 152, also tracks a running minimum.