Fixed-size window: max sum

Step 1: Fixed-size window: max sum

Streaming metrics often ask: over any window of k consecutive readings, what is the largest total? A naive approach re-sums every window in O(n*k). The sliding-window trick keeps a running total and updates it in O(1) per step by adding the incoming element and subtracting the one that just left the window.

Implement max_sum_window(nums, k) returning the maximum sum of any contiguous window of size k.

Rules:

  • If k is not a valid window size (k less than or equal to 0, or k greater than len(nums)), return None.
  • Otherwise compute the first window sum, then slide: add nums[i] and drop nums[i - k], tracking the best sum seen.

Example: max_sum_window([2, 1, 5, 1, 3, 2], 3) is 9, from the window [5, 1, 3].

Hints
Starter code
def max_sum_window(nums, k):
    # TODO: return the maximum sum of any contiguous window of size k.
    # Return None if k <= 0 or k > len(nums).
    # Compute the first window sum, then slide by adding the new element
    # and subtracting the element leaving the window.
    pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.