We use a Monotonic Deque to store indices of potential maxima. The deque will maintain indices in decreasing order of their corresponding values in nums.
- Initialize
q = deque(),output = []. - Iterate
rfrom 0 tolen(nums)-1:- While
qis not empty andnums[q[-1]] < nums[r],q.pop(). q.append(r).- If
l > q[0],q.popleft()(out of window). - If
r + 1 >= k,output.append(nums[q[0]]), incrementl.
- While
- Return
output.
- Time Complexity: O(N).
- Space Complexity: O(K).
from collections import deque
def max_sliding_window(nums, k):
output = []
q = deque() # indices
l = r = 0
while r < len(nums):
# pop smaller values from q
while q and nums[q[-1]] < nums[r]:
q.pop()
q.append(r)
# remove left val from window
if l > q[0]:
q.popleft()
if (r + 1) >= k:
output.append(nums[q[0]])
l += 1
r += 1
return output