nathanwailes

LeetCode 239 - Sliding Window Maximum - NeetCode solution

Oct 20th, 2023
824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | None | 0 0
  1. class Solution:
  2.     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
  3.         output = []
  4.         q = collections.deque() # index
  5.         l = r = 0
  6.  
  7.         while r < len(nums):
  8.             # pop smaller values from q
  9.             while q and nums[q[-1]] < nums[r]:
  10.                 q.pop()
  11.             q.append(r)
  12.  
  13.             # remove left val from window
  14.             if l > q[0]:
  15.                 q.popleft()
  16.            
  17.             if (r + 1) >= k:
  18.                 output.append(nums[q[0]])
  19.                 l += 1
  20.             r += 1
  21.        
  22.         return output
Advertisement
Add Comment
Please, Sign In to add comment