Beginner 5 min
Sliding windows
A sliding window keeps a contiguous range and updates its result as the range moves.
How it works
Imagine a moving frame around the current items. For a frame of size two, the move from [2, 5] to [5, 1] shares the 5. Subtract 2 and add 1, then compare the new total with the best so far. After the first frame, each shift is constant work.
Walk through an example
For a window of size 2 over [2, 5, 1, 4], the first sum is 7. Move one position by removing 2 and adding 1, which gives 6 without adding the whole window again.
What to watch for
A fixed-size window must fit inside the input. Rules for growing or shrinking a variable-size sum window can fail on negative inputs.
Code example
def max_window(a, k):
if not 1 <= k <= len(a): raise ValueError('invalid window')
total = best = sum(a[:k])
for i in range(k, len(a)):
total += a[i] - a[i - k]
best = max(best, total)
return bestCheck your understanding
What is the largest window sum?
See the example and explanation
- Worked example
- Given
[2, 5, 1, 4], window size 2 - Answer
7
The consecutive sums are 2 + 5 = 7, 5 + 1 = 6, and 1 + 4 = 5.