Data Structures19 sections · 729 units
Open in Course

Sliding Max - Algorithm

Maintain monotonicity

For each index ii:

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

2.2. Remove indices from back while nums[i]>=nums[deque.back()]nums[i] >= nums[deque.back()]. These can never be the answer.

3.3. Push ii to back.

4.4. If i>=k1i >= k - 1 (window is full), the front is the maximum. Each index is pushed once and popped at most once. Total: O(n)O(n). Time: O(n)O(n). Space: O(k)O(k).