Advertisement
hoangreal

Max Sliding Window (O(n))

Oct 21st, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. """
  2. Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right.
  3.  
  4. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
  5. """
  6.  
  7. """
  8. Idea: using deque
  9. 1. Deque right pointer should NEVER point to elements smaller than current element
  10. 2. Deque left pointer should NEVER point to elements outside our sliding window
  11. """
  12.  
  13. from collections import deque
  14.  
  15. class Solution:
  16.     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
  17.         q = deque()
  18.         ans = []
  19.         for i, v in enumerate(nums):
  20.             if q and i - k + 1 > q[0]:
  21.                 q.popleft() # remove index if out of window left
  22.             while q and nums[q[-1]] <= v: # `<=`, not `<`, to ensure the bigger index stored in deque
  23.                 q.pop()
  24.             q.append(i)
  25.             if i >= k - 1:
  26.                 ans.append(nums[q[0]])
  27.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement