Codele / Algorithms
Sliding window
Which 3 days in a row sold the most? Instead of adding up every group from scratch, slide a frame along the row: add the day that comes in, drop the day that leaves.
- A window is a block of k neighbours in a row. A sliding window moves it one step at a time.
- Do not add the whole window again. Add the one that comes in and take away the one that leaves.
- The first window is added once, the slow way. Every later window costs one add and one take-away.
- Keep a best so far box and update it only when the new sum is bigger.
- Adding from scratch costs about k times the number of windows. Sliding costs about the length of the row.
Loading the playable lesson…