<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>

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        
        # 超时
        '''
        if k < 1:
            return []
        if len(nums) < k:
            return max(nums)

        res = []
        res.append(max(nums[:k]))
        for l in range(1,len(nums)-k+1):
            r = l+k
            
            if nums[r-1] >= res[l-1]: #如果右边新加入的数大于等于前一个滑动窗口的最大值，则当前滑动窗口的最大值为新加入的数
                res.append(nums[r-1])
            elif nums[l-1] < res[l-1]:  #如果左边删除的数小于前一个滑动窗口的最大值，则当前滑动窗口的最大值等于上一个滑动窗口的最大值
                res.append(res[l-1])
            else:  #如果左边删除的数等于前一个滑动窗口的最大值 且 右边新加入的数小于前一个滑动窗口的最大值
                res.append(max(nums[l:r]))

        return res
        '''

        res = []
        q = deque()

        #维护长度为k的非增队列
        for idx, num in enumerate(nums):
            while q and q[-1] < num: 
                q.pop()
            q.append(num)

            if idx >= k and nums[idx - k] == q[0]: 
                q.popleft()
            
            if idx >= k - 1:
                res.append(q[0])
        
        return res

30241