Data Structures19 sections · 729 units
Open in Course

Why Monotonic Deque Works

The core idea

For sliding window maximum:

1.1. Store indices (not values) in the deque, so you can check if elements are in the current window.

2.2. Maintain decreasing order: nums[deque.front()] >= nums[deque.back()].

3.3. When adding index ii, remove indices from the back while nums[i] >= nums[deque.back()]. Smaller elements can't be the maximum while ii is in the window.

4.4. Remove indices from the front that are outside the window (index <ik+1< i - k + 1).

5.5. The front is always the maximum of the current window.