> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/array/239.-sliding-window-maximum.md).

# 239. 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.

**Follow up:**\
Could you solve it in linear time?

```cpp
// Max Heap
vector<int> maxSlidingWindow(vector<int>& nums, int k) { // time: O(nlogk); space: O(n)
    if (nums.empty() || k <= 0) return vector<int>();
    vector<int> res;
    priority_queue<pair<int, int> > pq;
    for (int i = 0; i < nums.size(); ++i) {
        while (!pq.empty() && pq.top().second <= i - k) pq.pop();
        pq.push({nums[i], i});
        if (i >= k - 1) res.push_back(pq.top().first);
    }
    return res;
}
```

```cpp
// Double-end queue
vector<int> maxSlidingWindow(vector<int>& nums, int k) { // time: O(n); space: O(n)
    if (nums.empty() || k <= 0) return vector<int>();
    vector<int> res;
    deque<int> dq; // stores index
    for (int i = 0; i < nums.size(); ++i) {
        if (!dq.empty() && dq.front() == i - k) dq.pop_front();
        while (!dq.empty() && nums[dq.back()] < nums[i]) dq.pop_back();
        dq.push_back(i);
        if (i >= k - 1) res.push_back(nums[dq.front()]);
    }
    return res;
}
```
