Given an array and a fixed window size k, find the maximum sum among all contiguous subarrays of exactly length k.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array and a fixed window size k, find the maximum sum among all contiguous subarrays of exactly length k.
The clean introductory fixed-size sliding window: recomputing every window's sum from scratch is O(n*k), but each window only differs from the last by one element leaving and one entering, so the sum can be updated in O(1) per slide.
Whenever a fixed-size window slides one position at a time across an array and you're tempted to resum the whole window every step, track a running window sum and update it incrementally: add the incoming element, subtract the outgoing one.
Compute the sum of the first window (indices 0 through k-1) directly by adding up its k elements — this is the only part of the algorithm that costs O(k). Track this as the current window sum and also as the best sum seen so far. Then slide the window one position at a time from index k to the end of the array: at each step, add the element now entering the window on the right and subtract the element that just left on the left, producing the new window's sum in O(1). Compare it to the best sum seen so far and keep the larger. By the end of the scan, every window of size k has been considered in O(n) total time rather than O(n*k).
class Solution {
public int maxSumSubarrayOfSizeK(int[] nums, int k) {
int windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += nums[i];
}
int best = windowSum;
for (int i = k; i < nums.length; i++) {
windowSum += nums[i] - nums[i - k];
best = Math.max(best, windowSum);
}
return best;
}
}