Fixed-size windows: add one, drop one
Summing every window of size k? Don't re-add k numbers each time: add the one entering and subtract the one leaving.
The idea
Neighbouring windows share all but two elements. Re-summing each window costs O(k) per window, O(n·k) in total. Instead keep a and update it in as the window slides.
Worked example
Max average of size-3 windows in [1, 12, -5, -6, 50, 3]
- First window 1 + 12 − 5 = 8
- Slide: + (−6) − 1 = 1
- Slide: + 50 − 12 = 39
- Slide: + 3 − (−5) = 47 → best sum 47, average 47/3
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
nums = [2, 1, 5, 1, 3, 2], k = 3
Solution · Pythonline 2
def max_average(nums, k):window = sum(nums[:k])best = windowfor i in range(k, len(nums)):window += nums[i] - nums[i - k]best = max(best, window)return best / kStep 1 of 5· line 2
Add up the first window once: 2 + 1 + 5 = 8.
- inside the window
time, O(1) space.
How to spot it
- “every of length k”, “window of size k”.
Common mistakes
- Subtracting nums[i - k + 1] instead of nums[i - k] (off by one).
- Starting best at 0 when sums can be negative.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Practise it
Go further
Up next for you · Beginner
“Have I seen this?” is a set →