Bug hunt

The Leaky Window

Sliding window: to find the best sum of k consecutive items, don't re-add all k numbers at every position (O(n·k)). Instead keep a running window sum. When the window slides one step, add the new item and subtract the one that fell out:

fuel:  [4, 2, 7, 1, 5],  k = 3
[4 2 7] 1 5   -> 13
4 [2 7 1] 5   -> 13 + 1 - 4 = 10
4 2 [7 1 5]   -> 10 + 5 - 2 = 12

That's O(n) no matter how big k is.

The bug report

An apprentice wrote best_window(fuel, k) to find the best k-day fuel total. The Guild noticed strange answers:

  • best_window([1, 2, 3, 4, 5], 2) returns 7, but the last two days give 9.
  • best_window([5, 1, 1], 2) returns 0, even though the first window is 6!

Assignment

Fix the two bugs in best_window so it returns the largest sum of any k consecutive values (assume 1 <= k <= len(fuel)). Keep the sliding-window approach.