Data Structures19 sections · 729 units
Open in Course

Shortest Subarray - The Idea

Using prefix sums

The sum of subarray from i+1i+1 to jj is prefix[j]prefix[i]prefix[j] - prefix[i]. You want this to be at least kk.

For each jj, you're looking for the largest i<ji < j such that prefix[j]prefix[i]kprefix[j] - prefix[i] \geq k, which means prefix[i]prefix[j]kprefix[i] \leq prefix[j] - k.

If prefix[i1]prefix[i2]prefix[i_1] \geq prefix[i_2] where i1<i2i_1 < i_2, then i1i_1 is never useful. Any jj that could use i1i_1 could use i2i_2 instead and get a shorter subarray. This "dominated" insight means you can use a monotonic deque.