easy

Maximum Sum Subarray of Size K

Find the maximum sum of any contiguous subarray of exactly size k.

1. Define the problem

Maximum Sum Subarray of Size K

Given an array of integers nums and a positive integer k, find the maximum sum of any contiguous subarray of exactly size k. Maintain a fixed length window of length k and update the running sum in O(1) as the window slides.

Constraints

  • 1 ≤ k ≤ nums.length
  • -104 ≤ numsi ≤ 104
  • nums.length ≥ 1

Example

Inputnums = [2, 4, 1, 3, 5], k = 2
Output8

Explanation The window [3, 5] has the largest sum of any size-2 window.

2. Know the words first

In plain terms

Contiguous subarray
A run of elements sitting right next to each other in the array, with nothing skipped — not just any subset you could pick.
3. Visualize the solution

Slide a fixed window of size 2

Slide a fixed window of size 2
Statusinit

Window [2, 4]: sum = 6 — best so far.

What happens in this step

window = [0, 1]  (size 2)

sum = 2 + 4 = 6

This is the first window, so it starts out as the best sum seen so far.
Step 1 of 4

Steps to visualize

  1. Place a window of length k on the first k elements and compute its sum.
  2. Record that sum as the best so far.
  3. Slide one step right: drop the leftmost value, add the new rightmost value.
  4. Update the best sum whenever the window sum improves.
  5. Stop when the window reaches the end of the array.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Slide a fixed window of size 2
Statusinit

Window [2, 4]: sum = 6 — best so far.

What happens in this step

window = [0, 1]  (size 2)

sum = 2 + 4 = 6

This is the first window, so it starts out as the best sum seen so far.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function maxSumSubarrayOfSizeK(nums, k) {
  if (k <= 0 || k > nums.length) {
    throw new Error("k must be between 1 and nums.length");
  }

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

  let maxSum = windowSum;

  for (let right = k; right < nums.length; right++) {
    const left = right - k;
    windowSum += nums[right] - nums[left];
    maxSum = Math.max(maxSum, windowSum);
  }

  return maxSum;
}
Time
O(n)
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
nums = [2, 4, 1, 3, 5], k = 28example from the docstring
nums = [7, -2, 5], k = 310smallest valid input: k === nums.length
nums = [3, 1, 9, 4], k = 19k === 1 just picks the max element
nums = [1, 1, 1, 1, 9, 9, 1], k = 218window must slide across the whole array to find the best sum
nums = [5, 5, 5, 5, 5], k = 315all identical elements
nums = [-1, -2, -3, -4], k = 2-3handles negative numbers
nums = [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 439larger, hand-verified case
nums = [1, 2], k = 5throwsthrows when k is larger than the array