Maintain fixed-size sliding windows
Quick answer
A fixed-size sliding window maintains an aggregate over k consecutive items. Instead of recomputing every sum, subtract the outgoing item and add the incoming item.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const a=[2,5,-1,4],k=2;let sum=a[0]+a[1];const sums=[sum];for(let i=k;i<a.length;i++){sum+=a[i]-a[i-k];sums.push(sum);}console.log(JSON.stringify(sums));Expected console output:
[7,4,3]Each update removes one value and adds the next.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function maxWindow(a,k){ let sum=0;for(let i=0;i<k;i++)sum+=a[i]; let best=sum; for(let i=k;i<a.length;i++){sum+=a[i]-a[i-k];best=Math.max(best,sum);} return best;}console.log(maxWindow([-4,-2,-7],2),maxWindow([-4,-2,-7],1));Expected console output:
-6 -2The first two-item window wins; the best singleton is -2.
How it works and cost model
For 1 <= k <= n, initialize the sum over the first k values and set best to that sum. At index i >= k, add a[i] and subtract a[i-k], then update best. The invariant is that sum covers exactly k items ending at i. With safe bounded integer arithmetic, time is O(n), auxiliary space O(1) when returning only the best sum. A variable-size window needs a separate invariant; shrinking on an excessive sum is not generally valid with negative values.
Common mistakes
Do not initialize the maximum to zero when all windows may have negative sums. Reject or explicitly define invalid k.
Practice
Compute all length-two window sums of [-4,-2,-7], then find the maximum. Test k=1 and k=length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maintain fixed-size sliding windows — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
What changes in a one-step shift of a fixed-size sum window?
Why initialize best with the first actual window sum?
When can a fixed-size window have exactly one valid position?
What is the exact console output in the Fixed-size rolling sum window example 1?
const a=[2,5,-1,4],k=2;let sum=a[0]+a[1];const sums=[sum];for(let i=k;i<a.length;i++){sum+=a[i]-a[i-k];sums.push(sum);}console.log(JSON.stringify(sums));What is the exact console output in the Fixed-size rolling sum window example 2?
function maxWindow(a,k){ let sum=0;for(let i=0;i<k;i++)sum+=a[i]; let best=sum; for(let i=k;i<a.length;i++){sum+=a[i]-a[i-k];best=Math.max(best,sum);} return best;}console.log(maxWindow([-4,-2,-7],2),maxWindow([-4,-2,-7],1));