Maximum sum of a fixed window
JavaScriptfunction maxSumFixed(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];
windowSum -= arr[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
console.log(maxSumFixed([2, 1, 5, 1, 3, 2], 3));Explanation
The first loop builds the initial window. After that, every step adds the entering element and removes the exiting element. This avoids recomputing the full sum for each new window.
Output
9
Real-life Example
A store can track the best 3-day sales streak by updating the rolling total each day instead of summing all 3 days from scratch every time.