---
# System prepended metadata

title: 239. Sliding Window Maximum
tags: [sliding window, Leetcode, python, Top 100 Liked Questions, hard]

---

###### tags: `Leetcode` `hard` `sliding window` `python` `Top 100 Liked Questions`

# 239. Sliding Window Maximum

## [題目連結:] https://leetcode.com/problems/sliding-window-maximum/

## 題目:
You are given an array of integers ```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 1:**
```
Input: nums = [1,3,-1,-3,5,3,6,7], 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
```
**Example 2:**
```
Input: nums = [1], k = 1
Output: [1]
```

## 解題想法:
* 題目為給一个數组、給了一个窗口大小k，每次向右滑動一个數字，求每次返回窗口内的數字中最大值。
* 解法可參考[1696. Jump Game VI](/g8JzXBXTRROo2DgG5xwxaQ) 思路
* 使用queue:
    * 目的為:
        * 存pos
        * que中位置對應到的nums值，呈現遞減
    * **step1:** 每次先判斷que中的位置，是否已經不在window size內的合理範圍，若不再則需popleft()
    * **step2:** 將que尾中位置的nums值，與當前nums[i]比較，若比當前小，則pop()
    * **step3:** 將當前i存入que
    * **step4:** 最後res每次存入nums[que[0]]即可
        * 因為que[0]一定是當前window size內nums之最大值

## Python:
``` python=
from collections import deque
class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        res=[]
        que=deque() #存位置
        #讓que中位置對應到的nums值，呈現遞減
        for i in range(len(nums)):
            #若que中最先進的位置已經不符合window size，則popleft
            #ex: que=[0,1,2,3] i=4, k=3
            #因為i一定要加入，當前判斷為2,3,4所以0,1需要pop
            while que and que[0]<=i-k:
                que.popleft()
            #若前輩比當前nums[i]小，淘汰
            while que and nums[que[-1]]<=nums[i]:
                que.pop()
            que.append(i)
            if i>=k-1:
                res.append(nums[que[0]])
        return res

if __name__=='__main__':
    result=Solution()
    ans=result.maxSlidingWindow(nums = [1,3,-1,-3,5,3,6,7], k = 3)
    print(ans) #[3, 3, 5, 5, 6, 7]
```