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
nums = [2, 4, 1, 3, 5], k = 28Explanation The window [3, 5] has the largest sum of any size-2 window.
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.
Slide a fixed window of size 2
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.
Steps to visualize
- Place a window of length k on the first k elements and compute its sum.
- Record that sum as the best so far.
- Slide one step right: drop the leftmost value, add the new rightmost value.
- Update the best sum whenever the window sum improves.
- Stop when the window reaches the end of the array.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
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.
Solution
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)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [2, 4, 1, 3, 5], k = 2 | 8 | example from the docstring |
nums = [7, -2, 5], k = 3 | 10 | smallest valid input: k === nums.length |
nums = [3, 1, 9, 4], k = 1 | 9 | k === 1 just picks the max element |
nums = [1, 1, 1, 1, 9, 9, 1], k = 2 | 18 | window must slide across the whole array to find the best sum |
nums = [5, 5, 5, 5, 5], k = 3 | 15 | all identical elements |
nums = [-1, -2, -3, -4], k = 2 | -3 | handles negative numbers |
nums = [1, 4, 2, 10, 23, 3, 1, 0, 20], k = 4 | 39 | larger, hand-verified case |
nums = [1, 2], k = 5 | throws | throws when k is larger than the array |