Dynamic Programming21 sections · 916 units
Open in Course

Shortest Subarray - Prefix Sums

Setting up the problem

Let P[i]P[i] = sum of first ii elements, with P[0]=0P[0] = 0. The sum of subarray [i,j)[i, j) is P[j]P[i]P[j] - P[i]. You want P[j]P[i]kP[j] - P[i] \geq k with j>ij > i, reducing jij - i. Rearranging: P[j]kP[i]P[j] - k \geq P[i]. For each jj, you're looking for the largest i<ji < j such that P[i]P[j]kP[i] \leq P[j] - k.

But you also want jij - i as small as possible, which means you want ii as large as possible while still satisfying the constraint.