Python coding

Best total over k consecutive days

amounts[i] is the net result of day i; it can be negative. Return the largest sum of any k consecutive days.

Constraints: 1 <= k <= len(amounts). Aim for O(n): do not add up each window from scratch.

Besides the tests, one large input (16,000 days) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • best_window_sum([2,5,1,8,2,9,1], 3) → 19
  • best_window_sum([4,-2,7,-5,6], 2) → 5
  • best_window_sum([-5,-2,-8,-1,-4], 2) → -5
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Fixed-size sliding window: the window always holds exactly k days and moves one day at a time.

Hint 2

Keep a running sum. When the window reaches index i, add amounts[i] and subtract amounts[i - k].

Hint 3

Start the best value from the sum of the first k days, not from 0: every window can be negative.

Solution and why it works
pythonO(n) · O(1)
def best_window_sum(amounts: list[int], k: int) -> int:
    window = sum(amounts[i] for i in range(k))
    best = window                              # the first real window, not 0
    for i in range(k, len(amounts)):
        window += amounts[i] - amounts[i - k]  # one day enters, one leaves
        best = max(best, window)
    return best

Neighboring windows share k − 1 values, so the next sum is the previous one plus the value that enters minus the value that leaves: O(1) per step instead of O(k). Start best from the first real window, not from 0: when every day is negative, so is the answer. The loop must reach the last index, or the final window is never checked.

Related lab: Sliding window, step by step