Optimize the code · Easy

Speed Up the Sliding Window Sum

Easy Make it fast Seen at Amazon, Uber

A metrics service needs the busiest period: maxWindowSum(nums, k) returns the largest sum of any k consecutive values.

The version below re-adds all k values for every window. With 100,000 samples and a window of 20,000 it is far too slow. Make it O(n) without changing the results.

Example 1

Input: nums = [1, 4, 2, 10, 2, 3, 1, 0, 20], k = 4
Output: 24
Explanation: The last window, [3, 1, 0, 20], sums to 24.

Constraints

  • 1 <= k <= nums.length

The slow code

Every case must finish within 300 ms (budgets are per language in the editor).

function maxWindowSum(nums, k) {
  let best = -Infinity;
  for (let start = 0; start + k <= nums.length; start++) {
    let sum = 0;
    for (let i = start; i < start + k; i++) sum += nums[i];
    best = Math.max(best, sum);
  }
  return best;
}

Hints

Hint 1

Two neighbouring windows share k - 1 values.

Hint 2

New sum = old sum + entering value - leaving value.

Make it faster

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Why it is slow: (n - k + 1) windows x k additions each, about 1.6 billion additions here.

The fix: sum the first window once, then slide: for each next position add the value entering the window and subtract the one leaving it. Every value is added once and removed once: O(n) total, independent of k.

Optimized solution

function maxWindowSum(nums, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) sum += nums[i];
  let best = sum;
  for (let i = k; i < nums.length; i++) {
    sum += nums[i] - nums[i - k]; // value entering minus value leaving
    best = Math.max(best, sum);
  }
  return best;
}

Common mistakes

  • Initialising the answer to 0 instead of the first window's sum (all-negative input).
  • Off-by-one on the value that leaves the window (i - k).

Follow-up questions

  • Maximum value (not sum) in each window: a monotonic deque.
  • Variable-size window: shortest subarray with sum at least S.