# 面试题59 - I

给定一个数组 nums 和滑动窗口的大小 k，请找出所有滑动窗口里的最大值。

```
示例:

输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7] 
解释: 

  滑动窗口的位置                最大值
---------------               -----
[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
```

## 提示：

* 你可以假设 k 总是有效的，在输入数组不为空的情况下，1 ≤ k ≤ 输入数组的大小。

## 注意：本题与主站 239 题相同：[https://leetcode-cn.com/problems/sliding-window-maximum/](https://leetcode-cn.com/problems/sliding-window-maximum/)

## Solutions

1. **Mono queue**

```cpp
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int> mq;
        for (int i = 0; i < nums.size() && i < k; i++) {
            while (!mq.empty() && mq.back() < nums[i])
                mq.pop_back();    
            mq.push_back(nums[i]);
        }

        vector<int> res;
        if (mq.size()) res.push_back(mq.front());
        for (int i = k; i < nums.size(); i++) {
            if (!mq.empty() && mq.front() == nums[i - k])
                mq.pop_front();
            while (!mq.empty() && mq.back() < nums[i])
                mq.pop_back();
            mq.push_back(nums[i]);
            res.push_back(mq.front());
        }

        return res;

    }
};
```

1. **dynamic programming**

```cpp
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int len = nums.size();
        if (!len)
            return {};
        if (len <= k)
            return {*max_element(nums.begin(), nums.end())};

        vector<int> left(len), right(len);
        left[0] = nums[0], right[len - 1] = nums[len - 1];

        for (int i = 1; i < len; i++) {
            if ((i + 1) % k == 0)
                left[i] = nums[i];
            else
                left[i] = max(left[i - 1], nums[i]);

            int j = len - i - 1;
            if ((j + 1) % k == 0)
                right[j] = nums[j];
            else
                right[j] = max(right[j + 1], nums[j]);
        }

        vector<int> res;
        for (int i = 0; i <= len - k; i++)
            res.push_back(max(right[i], left[i + k - 1]));

        return res;
    }
};
```
