What interviewers ask next
What if the numbers can be negative?
The window needs the property from before: once a window breaks the rule, growing it can't fix it. Totals of numbers that are never negative have it. Totals with negative numbers don't, because a negative entry can bring an over-budget stretch back under.
Take [5, -4, 3] with a budget of 4, and shrink while the total is over budget:
| Budget 4 | Window | Total |
|---|---|---|
| right 0 | 5 | 5, over: drop the 5 |
| right 1 | -4 | -4, length 1 |
| right 2 | -4, 3 | -1, length 2 |
The whole list totals 5 - 4 + 3 = 4, length 3, and the window never looked at it.
The window drops the 5 at the first step and reports 2. But the whole list totals 4, so the answer is 3.
What replaces the window is prefix sums: running totals that start at 0. Write prefix[i] for the total of the first i values, so prefix[0] is 0, the total of no values. The values from index a to index b then total prefix[b + 1] - prefix[a]: everything up to the end of the stretch, minus everything before its start.
Prefix sums of 4, -1, 2, 1, -2, 3, 0, 2 are 0, 4, 3, 5, 6, 4, 7, 7, 9. What do the values at indexes 1 to 5 total, from the -1 to the 3?