# 239. Sliding Window Maximum (Hard)

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?

## Solutions

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

int len = nums.length;
int[] ans = new int[len - k + 1];
int index = 0;

// Use a deque to store index
Deque<Integer> qmax = new ArrayDeque<>();
for (int i = 0; i < len; i++) {

// Remove the head of deque when index equals to (i-k) since it's out of window k
if (!qmax.isEmpty() && qmax.getFirst() == i - k) {
qmax.removeFirst();
}

// The following statement will not increase the time complexity since the maximum times of
// operations of adding elements to qmax is less than length of nums. Therefor, the time
// complexity of this solution is at most O(2n)=O(n)

// Remove numbers that no bigger than nums[i] in window k as they are negligible and useless.
while (!qmax.isEmpty() && nums[qmax.getLast()] <= nums[i]) {
qmax.removeLast();
}

// The head of qmax must be >= nums[i] since it's not removed. Index in the front of qmax
// must be local maximum except these before it

// The deque qmax keeps index while the array ans keeps value
if (i >= k - 1) {
ans[index++] = nums[qmax.getFirst()];
}
}

return ans;
}
}
``````