Jaya’s frame over the belt of rice bags: how many bags are read for the total of k when the frame slides? The longest run with no repeated variety, the max of…
Why it matters
Moving averages on a chart, per-minute API rate limits, the longest substring, spike detection: all sliding windows. The key is one question: can what leaves be "undone"? A total can (subtract it), varieties can (note them in a Map), a maximum cannot, and needs a queue.
The key idea
Two neighbouring frames share almost everything
Common mistakes
Recounting every window from zero Neighbouring windows share k − 1 elements. Just update: jumlah += in - out. O(n·k) becomes O(n).
Using a running total for a max A max cannot be "undone" when its element leaves: who is second? It needs an ordered queue of candidates (a monotonic deque), or a rescan when the window is narrow.
Confusing fixed and dynamic windows Fixed: width k, sliding one at a time. Dynamic: the right edge advances, the left edge catches up when the rule breaks (the longest substring, the shortest stretch that is enough).
Try it in this playground
Slide to the end The total of k bags with the sliding window: two reads per slide.
Recount Run the recount way and compare its reads.
The left edge jumps The run with no repeated variety: watch kiri jump past the repeat.
The max queue The max of every frame with the queue.