Created
December 3, 2020 15:24
-
-
Save anish000kumar/ba0f111ae7b5ecd37a888b4f87125788 to your computer and use it in GitHub Desktop.
Sliding window maximum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Author
anish000kumar
commented
Dec 3, 2020
- 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