Skip to content

Instantly share code, notes, and snippets.

@anish000kumar
Created December 3, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anish000kumar/ba0f111ae7b5ecd37a888b4f87125788 to your computer and use it in GitHub Desktop.
Save anish000kumar/ba0f111ae7b5ecd37a888b4f87125788 to your computer and use it in GitHub Desktop.
Sliding window maximum
from collections import deque
def maxSlidingWindow(nums, window_size):
start, ans = 0, []
q = deque();
for end in range(len(nums)):
while q and nums[end] > nums[q[-1]]: q.pop()
q.append(end)
if end >= window_size-1:
ans.append(nums[q[0]])
start += 1
while q and q[0] < start: q.popleft()
return ans
@anish000kumar
Copy link
Author

  • When end pointer moves forward: add element to queue, ensuring the max value stays at 0th index
  • When start pointer moves forward: remove from queue, which were processed in previous windows. i.e remove all indexes less than first index in queue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment