Dynamic Programming21 sections · 916 units
Open in Course

Sliding Maximum - The Pattern

Decreasing queue

Use a monotonic decreasing deque. Store indices, not values. The front always holds the index of the current maximum. When processing index ii: First, remove indices from the front that are outside the window (index <ik+1< i - k + 1).

Second, remove indices from the back while nums[back]nums[i]nums[back] \leq nums[i]. Third, add ii to the back. Why remove smaller elements? Because nums[i]nums[i] is both larger AND enters later. Those smaller elements will never be the maximum while nums[i]nums[i] is in the window.