nathanwailes

LeetCode 239 - Sliding Window Maximum - 2022.12.31 solution

Dec 31st, 2022
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.46 KB | None | 0 0
  1. class Solution:
  2.     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
  3.         """ How to solve it: From the way the window is sliding across the nums, you can imagine a deque
  4.        where numbers are added to the right and popped off the left.  The tricky part is knowing exactly how
  5.        to add to and pop from the deque.  If the deque contains every value, you'll need to look through it each
  6.        time to find the max, which will make the solution O(n*k).
  7.        We need some way to remove items from the deque when they're 'old'.
  8.        I think one key observation you can make from looking at the first window in the first example ([1 3 -1])
  9.        is that we don't need the deque to contain the '1', because the '3' will always be the max for that window
  10.        and any future window (because the window will always move to the right).  So the starting data for the
  11.        deque could be the 3 and the -1.  We'd want the -1 because it *could* conceivably be the max for the window
  12.        as it moves to the right.  When the window moves to the right one spot, if the value was greater than 3
  13.        (like, 4) we could discard the existing values in the deque (3 and -1) because they could never be the
  14.        max anymore.  If the value was greater than -1 but less than 3, we could discard the -1 because it would
  15.        never be the max anymore, but we'd need to keep the 3 for the current window.  And if the value was less
  16.        than -1, we'd need to keep the 3, the -1, and the new value (in this case -3) because the 3 would be the
  17.        max for the current window, the -1 could be the max when the 3 gets popped, and the -3 could end up being
  18.        the max when both the 3 and -1 are no longer in the window.  All of this suggests maintaining the deque
  19.        in decreasing order.
  20.        """
  21.         d = deque()
  22.         res = []
  23.  
  24.         for i in range(len(nums) - k + 1):
  25.             if not d:
  26.                 for j in range(k):
  27.                     if not d:
  28.                         d.append(i+j)
  29.                     else:
  30.                         while d and nums[i+j] > nums[d[-1]]:
  31.                             d.pop()
  32.                         d.append(i+j)
  33.             elif i+k <= len(nums):
  34.                 while d and d[0] < i:
  35.                     d.popleft()
  36.                 while d and nums[i+k-1] > nums[d[-1]]:
  37.                     d.pop()
  38.                 d.append(i+k-1)
  39.             res.append(nums[d[0]])
  40.         return res
Advertisement
Add Comment
Please, Sign In to add comment