Dynamic Programming21 sections · 916 units
Open in Course

Shortest Subarray - The Idea

Monotonic increasing queue

Use a monotonic increasing queue of indices by prefix sum value. Two observations:

1.1. If P[i1]P[i2]P[i_1] \geq P[i_2] and i1<i2i_1 < i_2, you never need i1i_1. Why? Index i2i_2 is closer to future jj values AND has equal or smaller prefix sum, so it gives a shorter valid subarray.

2.2. Once index ii forms a valid subarray with jj (meaning P[j]P[i]kP[j] - P[i] \geq k), you can remove ii from the deque. Future positions j>jj' > j would give longer subarrays with ii.