Fixed-size window (e.g. max sum of size-k subarray)
corebeginnerA fixed-size window of exactly k elements slides across an array one step at a time — only the element leaving and the element entering change the running total, so nothing needs to be resummed.
Think of it as
Picture a k-wide frame sliding across the array. Build the total for the first k elements once. Each time the frame slides one step right, subtract the element that just left it and add the element that just entered — the new total is always one subtraction and one addition away from the last one.
What we're doing: Find the maximum sum of any contiguous size-k subarray.
- 2
- The first window is built once, the ordinary way — there is nothing to slide from yet.
- 4
- nums[i] just entered the window; nums[i - k] just left it — exactly k elements are in the window at every step.
9Why this works: The window [1, 5, 1] → sum 7 slides to [5, 1, 3] → sum 9 by removing the leading 1 and adding the trailing 3 — no resumming. 9 turns out to be the best of all four size-3 windows.
Recomputing sum(nums[i:i+k]) at every window position
Wrong
Better
What you see: max_sum_fixed_window_slow gives the same correct answer (9) here, then times out once n and k both grow large (e.g. n ~ 10⁵, k ~ 10⁴).
Why: sum(nums[i:i+k]) resums all k elements from scratch at every one of the n - k + 1 positions — O(n × k) total. Updating the running total by one subtraction and one addition per step drops that to O(n).
- Maximum Average Subarray IeasyLeetCode
Exactly the example above — track the running sum and divide by k at the end.
- Sliding Window MaximumhardLeetCode
The window is still fixed-size, but the state (the running maximum) is not a simple running total — a monotonic deque is needed to update it in O(1) amortized per step.
Remember: A fixed window updates by subtracting the outgoing element and adding the incoming one — resumming the whole window at every position is the O(n × k) trap this pattern exists to avoid.