Blueprints · Sliding Window

Sliding Window: Maximum Sum of k Consecutive Elements

One problem, three stages: make it work, make it fast, make it lean. Step through each stage in the visualizer, then run all three on a big input in the benchmark and watch the brute force overheat.

The real-world version

A monitoring dashboard shows the busiest 5-minute stretch of the day from per-second request counts: 86,400 numbers per server, recomputed for every server in the fleet.

The problem

Given an array of integers nums and a window size k, return the largest sum of any k consecutive elements.

nums = [2, 1, 5, 1, 3, 2, 9, 4], k = 3  →  15   # 2 + 9 + 4

X-ray: watch it run

Benchmark: will the forge overheat?

Run all three stages on a large input in your browser and compare the work each one does.

In the interview

Fixed-size windows like this one are the warm-up. The follow-up is usually a variable window ("longest substring without repeats"), where the left edge moves only when a rule breaks, and the same add/remove idea applies.