# Sliding Window Maximum

https://leetcode.com/problems/sliding-window-maximum/

Given an array 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:

```Input: nums = `[1,3,-1,-3,5,3,6,7]`, and 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
```

Note:
You may assume k is always valid, 1 ≤ k ≤ input array‘s size for non-empty array.

Could you solve it in linear time?

1. 当sliding window往右滑动的时候，要将左侧已经滑出窗口的元素从队列头部删除（如果它还在队列里的话）。

2. 将x塞进队列前，对队列从后往前遍历，把小于x的所有元素都弹出。

因为此时队列内元素在array中都是在x左侧的，所以如果他们小于x，是没有希望成为sliding window内的最大元素的，所以删除。

注意，这一步不能从deque的头部开始，因为头部的元素是最大的，很有可能已经比x大，就直接结束了。然而，后面还有小于x的元素不能被弹出。

```class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length == 0) {
return new int[0];
}

int[] res = new int[nums.length - k + 1];

for (int i = 0; i < nums.length; i++) {
if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) {
deque.pollFirst();
}
while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
deque.pollLast();
}
deque.offer(i);
if (i >= k - 1) {
res[i - k + 1] = nums[deque.peekFirst()];
}
}

return res;
}
}```

Sliding Window Maximum

(0)
(0)

0条