Sliding Window
When to use: contiguous subarray/substring with a constraint ("longest/shortest/count of windows such that …") where expanding/shrinking the window changes the constraint monotonically.
- Variable window: grow
revery step; while the window is invalid, shrinkl. Answer is updated when valid. - Fixed window of size k: add
a[r], removea[r-k]. - Needs non-negative numbers for sum constraints — with negatives use prefix sums (see 560).
l = 0
for r, x in enumerate(a):
add(x)
while invalid():
remove(a[l]); l += 1
best = max(best, r - l + 1)
Problems
Showing 20 of 20