|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/sliding-window-maximum/ |
| 3 | + |
| 4 | +You are given an array of integers nums, there is a sliding window of size k which is moving |
| 5 | +from the very left of the array to the very right. You can only see the k numbers in the window. |
| 6 | +Each time the sliding window moves right by one position. |
| 7 | +Return the max sliding window. |
| 8 | + |
| 9 | +Example 1: |
| 10 | +Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 |
| 11 | +Output: [3,3,5,5,6,7] |
| 12 | +Explanation: |
| 13 | +Window position Max |
| 14 | +--------------- ----- |
| 15 | +[1 3 -1] -3 5 3 6 7 3 |
| 16 | + 1 [3 -1 -3] 5 3 6 7 3 |
| 17 | + 1 3 [-1 -3 5] 3 6 7 5 |
| 18 | + 1 3 -1 [-3 5 3] 6 7 5 |
| 19 | + 1 3 -1 -3 [5 3 6] 7 6 |
| 20 | + 1 3 -1 -3 5 [3 6 7] 7 |
| 21 | + |
| 22 | +Example 2: |
| 23 | +Input: nums = [1], k = 1 |
| 24 | +Output: [1] |
| 25 | + |
| 26 | +Constraints: |
| 27 | +1 <= nums.length <= 105 |
| 28 | +-104 <= nums[i] <= 104 |
| 29 | +1 <= k <= nums.length |
| 30 | +""" |
| 31 | +# Time Complexity: O(N) |
| 32 | +class Solution: |
| 33 | + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: |
| 34 | + next_greater = [0] * len(nums) |
| 35 | + stack = [] |
| 36 | + |
| 37 | + for index in range(len(nums)-1, -1, -1): |
| 38 | + while stack and nums[stack[-1]] <= nums[index]: |
| 39 | + stack.pop() |
| 40 | + |
| 41 | + next_greater[index] = stack[-1] if stack else len(nums) |
| 42 | + stack.append(index) |
| 43 | + |
| 44 | + res = [] |
| 45 | + max_index = 0 |
| 46 | + for index in range(len(nums) - k + 1): |
| 47 | + if max_index < index: |
| 48 | + # to handle case where greater element of last window was the first one which is removed from the window |
| 49 | + max_index = index |
| 50 | + while next_greater[max_index] < index + k: |
| 51 | + max_index = next_greater[max_index] |
| 52 | + |
| 53 | + res.append(nums[max_index]) |
| 54 | + |
| 55 | + return res |
0 commit comments