<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>

<p>Return <em>the max sliding window</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3
<strong>Output:</strong> [3,3,5,5,6,7]
<strong>Explanation:</strong> 
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       <strong>3</strong>
 1 [3  -1  -3] 5  3  6  7       <strong>3</strong>
 1  3 [-1  -3  5] 3  6  7      <strong> 5</strong>
 1  3  -1 [-3  5  3] 6  7       <strong>5</strong>
 1  3  -1  -3 [5  3  6] 7       <strong>6</strong>
 1  3  -1  -3  5 [3  6  7]      <strong>7</strong>
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> [1]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= k &lt;= nums.length</code></li>
</ul>


#define pint pair<int, int>
#define vint vector<int>
#define vll vector<long long>
#define vpint vector<pair<int, int>>
#define vstr vector<string>
#define uset unordered_set
#define umap unordered_map
#define vbool vector<bool>
#define vvint vector<vector<int>>
#define vvvint vector<vector<vector<int>>>
#define ll long long
#define MOD 1000000007

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int n = nums.size();

        deque<int> dq;

        for(int i = 0; i < k - 1; i++) {
            if(dq.empty())
                dq.push_back(nums[i]);
            
            else if(dq.back() < nums[i]) {
                while(!dq.empty() && (dq.back() < nums[i]))
                    dq.pop_back();

                dq.push_back(nums[i]);
            }

            else
                dq.push_back(nums[i]);
        }

        vint ans(n - k + 1);

        for(int i = 0; i <= n - k; i++) {
            if(dq.empty())
                dq.push_back(nums[i + k - 1]);
            
            else if(dq.back() < nums[i + k - 1]) {
                while(!dq.empty() && (dq.back() < nums[i + k - 1]))
                    dq.pop_back();

                dq.push_back(nums[i + k - 1]);
            }

            else
                dq.push_back(nums[i + k - 1]);

            ans[i] = dq.front();

            if(nums[i] == dq.front())
                dq.pop_front();
        }

        return ans;
    }
};
133108