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:
Example: max_sum_window([2, 1, 5, 1, 3, 2], 3) is 9, from the window [5, 1, 3].
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
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
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:
Example: max_sum_window([2, 1, 5, 1, 3, 2], 3) is 9, from the window [5, 1, 3].
Press Run Tests or ββ© to check your solution.