Easy · Sliding Window
Understand → Visualise → Practice.
Many array problems ask about every block of k neighbouring values. Recomputing each block from scratch wastes work.
Keep a running window total. When the window slides one place, add the value that enters and subtract the value that leaves.
Sum the first k values.
window += nums[i] − nums[i − k].
Keep the largest total seen.
Recomputing each window is O(n·k). The sliding window is O(n) time and O(1) space.
The answer can be negative; start `best` from the first window, not from 0.
Read the full guides first: Big-O and Complexity, Arrays and Dynamic Arrays, Prefix Sums and Difference Arrays.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.