A moving slice of neighbouring elements that glides across an array in one pass, updating a running total instead of re-scanning.
A sliding window is a contiguous slice of an array that glides across it one step at a time. The trick is that when the window moves, almost everything inside it stays the same — so instead of recomputing the slice from scratch, you add the value entering on the right and subtract the value leaving on the left. That turns what looks like nested work into a single left-to-right pass.
Suppose you want the largest sum of any 3 neighbouring numbers in [2, 1, 5, 1, 3, 2]. The brute-force way re-adds three numbers for every position — and if the window were width k over n elements that's O(n·k) work. But consecutive windows overlap almost entirely, so re-summing throws away answers you already had.
arr[0..k-1].arr[r] and subtract the leaving element arr[r-k].[2, 1, 5] → sum 8. best = 8.+1 (enters), -2 (leaves) → 8 - 2 + 1 = 7. Window [1, 5, 1].+3, -1 → 7 - 1 + 3 = 9. Window [5, 1, 3]. best = 9.+2, -5 → 9 - 5 + 2 = 6. Window [1, 3, 2].function maxSumK(arr, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += arr[i]; // first window
let best = sum;
for (let r = k; r < arr.length; r++) {
sum += arr[r] - arr[r - k]; // add entering, drop leaving
best = Math.max(best, sum);
}
return best;
}
// maxSumK([2, 1, 5, 1, 3, 2], 3) === 9