| 1 | import collections |
| 2 | |
| 3 | class Solution(object): |
| 4 | def maxSlidingWindow(self, nums, k): |
| 5 | # Result list to store the maximum of each sliding window |
| 6 | output = [] |
| 7 | |
| 8 | # Deque to store indices of useful elements in the current window |
| 9 | # The deque will always be in decreasing order of their values in nums |
| 10 | q = collections.deque() |
| 11 | |
| 12 | # Left (l) and right (r) pointers for the sliding window |
| 13 | l = r = 0 |
| 14 | |
| 15 | # Iterate until the right pointer reaches the end of the array |
| 16 | while r < len(nums): |
| 17 | # Remove elements smaller than the current element nums[r] |
| 18 | # from the back of the deque, since they can’t be maximum anymore |
| 19 | while q and nums[q[-1]] < nums[r]: |
| 20 | q.pop() |
| 21 | |
| 22 | # Add the current index to the deque |
| 23 | q.append(r) |
| 24 | |
| 25 | # Remove indices from the front of the deque that are out of the current window |
| 26 | if l > q[0]: |
| 27 | q.popleft() |
| 28 | |
| 29 | # If the window has reached size k, start adding maximums to output |
| 30 | if (r + 1) >= k: |
| 31 | # The element at the front of the deque is the maximum for this window |
| 32 | output.append(nums[q[0]]) |
| 33 | # Move the left boundary to slide the window forward |
| 34 | l += 1 |
| 35 | |
| 36 | # Move the right boundary to expand the window |
| 37 | r += 1 |
| 38 | |
| 39 | # Return the list of maximums for each window |
| 40 | return output |
| 41 | |
| 42 | |
| 43 | # Test the solution |
no outgoing calls
no test coverage detected