You are given an array of integers nums
. There is a sliding window of size k
which is moving from the very left of the array to the very right. 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.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length
A naive approach would be to iterate through the array with a sliding window of size k
. For each window, find the maximum element. This involves iterating k
times for each window.
Code (Python):
def max_sliding_window_brute_force(nums, k):
if not nums:
return []
result = []
for i in range(len(nums) - k + 1):
window = nums[i:i+k]
result.append(max(window))
return result
Big O Analysis:
nums
and k is the window size. This is because for each of the n-k+1 windows, we iterate through k elements to find the maximum.nums
and k
is the size of the sliding window, to store the output array. Can be O(1) if the result is computed in place.A more efficient solution utilizes a double-ended queue (deque) to maintain a decreasing order of indices of potentially maximum elements within the window.
Algorithm:
nums
.i - k + 1
).i >= k - 1
), the front of the deque contains the index of the maximum element in the current window. Add this element to the result.Code (Python):
from collections import deque
def max_sliding_window(nums, k):
if not nums:
return []
d = deque()
result = []
for i in range(len(nums)):
# Remove elements out of the window
while d and d[0] <= i - k:
d.popleft()
# Remove smaller elements in deque than current element
while d and nums[d[-1]] <= nums[i]:
d.pop()
d.append(i)
# Add max to results
if i >= k - 1:
result.append(nums[d[0]])
return result
Big O Analysis:
nums
. Each element is added and removed from the deque at most once.Edge Cases:
k
is 1: Return the original array.k
is equal to the length of nums
: Return an array with a single element, which is the maximum of nums
.k
is greater than the length of nums
: This violates the constraint. Should throw an IllegalArgumentException.