This post shows how to find the maximum sum subarray of size K in JavaScript using the Sliding Window technique — one of the most frequently asked array patterns in coding interviews.

Maximum sum subarray of size K (Sliding Window) in JavaScript:

Explanation:
A naive approach recalculates the sum of every window of size K from scratch, which takes O(n*k) time. The sliding window technique instead keeps a running sum: as the window slides forward by one position, we subtract the element leaving the window and add the element entering it. This brings the time complexity down to O(n), since each element is only added and removed from the sum once.


JavaScript Program to Find Maximum Sum Subarray of Size K

function maxSumSubarray(arr, k) {
  let windowSum = 0;

  for (let i = 0; i < k; i++) {
    windowSum += arr[i];
  }

  let maxSum = windowSum;

  for (let i = k; i < arr.length; i++) {
    windowSum += arr[i] - arr[i - k];
    maxSum = Math.max(maxSum, windowSum);
  }

  return maxSum;
}

const numbers = [2, 1, 5, 1, 3, 2];
const k = 3;

console.log(`Maximum sum of subarray of size ${k}:`, maxSumSubarray(numbers, k));

Output:

Maximum sum of subarray of size 3: 9

The sliding window pattern is one of the highest-value techniques to master for interviews, since it shows up in dozens of variations. See more array and string problems in our Interview Prep section, or practice daily with our Problem of the Day.


Frequently Asked Questions About the Sliding Window Technique

What is the Sliding Window technique?

Sliding Window is a technique for solving array or string problems by maintaining a "window" of elements and sliding it across the data, updating a running result incrementally instead of recalculating it from scratch for every position.

Why is the sliding window approach faster than a brute-force solution?

A brute-force solution recalculates the sum (or other value) for every window from scratch, taking O(n*k) time. Sliding window reuses the previous window's result and updates it in O(1) per step, bringing the total time down to O(n).

When should I use the sliding window technique?

Use it whenever a problem asks about a contiguous subarray or substring of a fixed or variable size — common signals include "maximum/minimum sum of size k," "longest substring with condition X," or "smallest subarray with sum at least X."