A window of fixed size: moving sums and averages
🌍 In real life. A tea stall owner writes down each day's sales. Every evening she wants the average of the last 3 days, to see the trend without one rainy day fooling her. On Thursday she could add Tuesday, Wednesday and Thursday from scratch, and on Friday add Wednesday, Thursday and Friday all over again. But two of those three numbers are the same as yesterday's! Today's total is just yesterday's total, plus today, minus the day that dropped out.
That little trick is the sliding window.
The idea in one sentence: keep a running total of the k items in the window, and when the window slides one place, add the item that comes in and subtract the one that goes out.
Its words:
- window: a stretch of k neighbours,
nums[l:l + k] - slide: move the window one place right: one item enters on the right, one leaves on the left
How it works, step by step:
- add up the first window once: k additions
- for each next position r:
total += nums[r] - nums[r - k] - after each slide, compare
totalwith the best so far
Watch the frame slide along a week of sales. Each slide changes the sum by just two numbers:
Why it is correct. The new window is the old one with exactly one item gone (on the left) and one added (on the right); every other item is in both. So old total − leaving + entering is exactly the new window's sum.
What it costs, worked out. Adding every window from scratch costs k additions for each of the n − k + 1 windows: for a year of sales (n = 365) and a 30-day window, 336 × 30 = 10,080 additions. Sliding costs 30 for the first window and then 2 per slide: 30 + 2 × 335 = 700. That is O(n) instead of O(n × k), with O(1) extra memory.
def max_window_sum(nums, k):
total = sum(nums[:k]) # the first window, once
best = total
for r in range(k, len(nums)):
total += nums[r] - nums[r - k] # one in, one out
best = max(best, total)
return best
sales = [12, 7, 9, 15, 10, 6, 14]
print(max_window_sum(sales, 3))
print([round(sum(sales[i:i + 3]) / 3, 1) for i in range(len(sales) - 2)])Mistakes and edge cases.
- off by one: the item leaving is
nums[r - k], notnums[r - k + 1] - starting
bestat 0 is wrong when every number is negative: start it at the first window's total - if k is bigger than the list, there is no window at all: decide what to return (the tasks say)
- for averages, keep the sum while sliding and divide at the end of each step, so rounding errors don't pile up
Quiz
The window [4, 1, 5] adds up to 10. It slides to [1, 5, 9]. What does this print?
total = 10 total += 9 - 4 print(total)With a window of size k over n items, how many additions and subtractions does sliding need in total?
- About k + 2(n − k): O(n)
- About k × n: O(n × k)
- About n²: O(n²)
What does this print?
nums = [2, 8, 1, 6] k = 2 total = best = sum(nums[:k]) for r in range(k, len(nums)): total += nums[r] - nums[r - k] best = max(best, total) print(best)For nums = [-5, -2, -9] and k = 1 this answers 0, though no window adds up to 0. Which line is wrong?
def max_window_sum(nums, k): total = sum(nums[:k]) best = 0 for r in range(k, len(nums)): total += nums[r] - nums[r - k] best = max(best, total) return best
Coding tasks
Write
max_window_sum(nums, k)in O(n) with a sliding window: the biggest sum of k neighbours (1 ≤ k ≤ len(nums)).Write
moving_averages(nums, k)with a sliding sum: the average of every window of k neighbours, in order, as floats. If k is bigger than the list, give back [].