The sliding window works on a contiguous piece of an array or string. When it slides one step, one element enters and one leaves, so instead of recomputing the answer we update it in O(1). It is a special case of the two pointers technique for contiguous subarrays.
![A window of length 3 slides over [2, 1, 5, 1, 3, 2]](img/lessons/algorithms/sliding-window-fixed-sums.svg)
The fixed-length window
Task: the maximum sum of k consecutive elements. Brute force recomputes every window: (n - k + 1) * k additions, i.e. O(nk). When the window slides, the new sum is old + a[i] - a[i - k].
def max_sum_k(a, k):
window = sum(a[:k]) # first window
best = window
for i in range(k, len(a)):
window += a[i] - a[i - k] # enter a[i], leave a[i - k]
best = max(best, window)
return best