Overview
Find the best run of k consecutive days with a running total: add the day that enters, subtract the day that leaves, and start from the first window, not from zero.
- running total instead of re-summing
- one step per day
- start with the first window (negative data)
Short Course
A sliding window keeps a running total: add the item that enters, subtract
the one that leaves. Each step is O(1) instead of re-summing k items. Trap:
start best at the first window, not at 0, or negative data breaks it.
window = sum(temps[:3])
for i in range(3, len(temps)):
window += temps[i] - temps[i - 3]
print(window / 3) # 3-day average
Task
Write best_window(sales, k): the largest total of k consecutive days, or
None when there are fewer than k days. Example:
best_window([3, 1, 4, 1, 5, 9, 2], 3) → 16.
Test Suites
Pending
Next
Output