1. First window
Sum the first k values once to seed the window.
for (let i = 0; i < k; i++)Typorithm · medium
Step 1 of 8 · intro card
Basic Patterns
A sliding window reuses the previous sum instead of re-adding k values.
Recomputing every window from scratch costs O(n·k). The window trick reuses overlap.
When the window slides one step, only one value enters and one value leaves.
Updating the running sum with that difference turns the whole scan into O(n).
Seed the sum with the first k values.
Slide: add entering, subtract leaving.
Track the best while sliding.
function maxWindowSum(arr, k) {
let sum = 0;
for (let i = 0; i < k; i++) {
sum += arr[i];
}
let best = sum;
for (let i = k; i < arr.length; i++) {
sum += arr[i] - arr[i - k];
best = Math.max(best, sum);
}
return best;
}Connect each part of the code to the concept before you type.
Sum the first k values once to seed the window.
for (let i = 0; i < k; i++)The first window is the best answer until a better one appears.
let best = sumAdd the entering value and subtract the leaving value in one step.
sum += arr[i] - arr[i - k]Compare the new window sum with the best seen so far.
best = Math.max(best, sum)After one pass, best holds the maximum window sum.
return bestRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.