Know this before you start: βFixed-size windows (every window of size k)β
Fixed-size sliding windows
To look at every block of k items, don't recompute each one: slide by one, add the item coming in and remove the one going out.
The idea
A window is a range [left, right] of the array. With a fixed size k, moving it one step changes only two items: one enters on the right, one leaves on the left.
Keep whatever you're measuring (a sum, a count) for the current window and update it with just those two items. That makes each step O(1) instead of O(k).
See it step by step
Largest sum of 3 consecutive numbers in [2, 1, 5, 1, 3, 2]
- First window [2, 1, 5] β 8
- Slide: +1 β2 β 7. Slide: +3 β1 β 9. Slide: +2 β5 β 6
- Best: 9 (the window [5, 1, 3]).
In code (Python)
def max_window_sum(nums, k):
window = sum(nums[:k])
best = window
for right in range(k, len(nums)):
window += nums[right] - nums[right - k] # in, out
best = max(best, window)
return best
print(max_window_sum([2, 1, 5, 1, 3, 2], 3)) # 9O(n) time, O(1) space.
When you'll use it
- βEvery subarray / substring of length kβ, averages over k, counts inside a block of k.
Common mistakes
- Removing nums[right β k + 1] instead of nums[right β k].
- Starting `best` at 0 when sums can be negative.