Fill the blank
Fill the blank so each step costs O(1).
sales, k = [3, -1, 4, 1, -5, 9], 3
window = sum(sales[:k])
best = window
for i in range(k, len(sales)):
window += ____
best = max(best, window)
print(best)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A sales[i] - sales[i - k]
Right: add the day entering and remove the day leaving.
Totals are 6, 4, 0 and 5, so the first window is the best here.
Why not the others?
- B sales[i]. Then the window never forgets old days and keeps growing.
- C sales[i] - sales[i - 1]. That removes the previous day, not the one leaving a window of size k.