Dynamic Programming21 sections · 916 units
Open in Course

Challenge: Negative Values

Why prefix sums help

With all non-negative values, sliding window (two pointers) finds shortest subarray with sum K\geq K in O(n)O(n). Negative values break monotonicity of cumulative sums.

Expanding the window can decrease the sum. Prefix sums + monotonic queue handle this. We maintain increasing prefixes because larger prefixes are better left bounds. observation: if prefix[i]prefix[j]prefix[i] \geq prefix[j] for i<ji < j, then ii is never a better left bound than jj for any future right bound.