Finds the maximum sum of any K consecutive elements. Instead of re-adding the whole window each time, it slides one step — subtracting the element that leaves and adding the one that enters.
Finds the maximum sum of any K consecutive elements. Instead of re-adding the whole window each time, it slides one step — subtracting the element that leaves and adding the one that enters.
Time complexity: O(n). Space complexity: O(1).
Core idea — Sum the first K elements once, then reuse that sum: each slide drops the leftmost element and adds the next one on the right.
What each pass accomplishes — Every slide costs just one subtraction and one addition to get the new window's sum, which is compared against the best so far. The window visits each element once, so the whole array is scanned in O(n) rather than O(n·K).
Use the interactive visualizer above to run Sliding Window (Max Sum of K) on your own input and watch every comparison, swap, and operation animate step by step — pause, scrub, or replay at any speed.