⚡Flashcard Drill➔
NeetCode #255LC-239HardSliding WindowNC 150NC 250
← Back to All Problems

#255 · #239 · Sliding Window Maximum(滑动窗口最大值)

📌 Problem Statement & Constraints

You are given an array nums and a window size k. A sliding window of size k moves from the left to the right of the array. Return an array of the maximum value in each window. Constraints: 1 <= nums.length <= 10^5, -10^4 <= nums[i] <= 10^4, 1 <= k <= nums.length.

💡 Core Algorithmic Approaches

  1. Maintain a monotonic deque of indices whose values are strictly decreasing from front to back.
  2. Before inserting a new index, pop from the back every index whose value is <= the new value -- they can never be the maximum again while the new element is in the window.
  3. Pop from the front any index that has fallen out of the window (<= i - k).
  4. The front of the deque is then the maximum of the current window, available in O(1).

💻 Benchmark Python3 Implementation

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        from collections import deque
        dq = deque()                   # indices, values decreasing
        res = []
        for i, x in enumerate(nums):
            while dq and nums[dq[-1]] <= x:
                dq.pop()               # dominated by the new element
            dq.append(i)
            if dq[0] <= i - k:
                dq.popleft()           # left the window
            if i >= k - 1:
                res.append(nums[dq[0]])
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each index is pushed once and popped at most once.
💾 Space Complexity
O(k) for the deque.

⚠️ Interview Pitfalls & Follow-ups

  • Storing values instead of indices: you cannot tell when an element leaves the window without its index.
  • Using < instead of <= in the back-popping comparison: with < the deque may hold equal values, which is correct but wasteful; <= keeps it strictly decreasing and is the usual choice.
  • Checking the window bounds before pushing: the front eviction must happen after the push, using the index comparison dq[0] <= i - k.
  • Emitting results before the first full window: the i >= k - 1 guard is required.
  • Recomputing max(window) for each position: O(n * k).
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

滑动窗口最大值

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。返回 滑动窗口中的最大值 。约束:1 ≤ nums.length ≤ 10^5;-10^4 ≤ nums[i] ≤ 10^4;1 ≤ k ≤ nums.length。

核心要点

  • 单调递减队列(标准解) :用双端队列保存 下标 ,队列中对应的值保持单调递减。
  • 入队前弹出队尾较小者 :加入新元素时,把队尾所有 ≤ 新元素的值弹出——它们不可能再成为任何窗口的最大值(因为新元素更大且更靠右)。
  • 弹出队首过期元素 :若队首下标 ≤ i − k ,说明它已滑出窗口,弹出。
  • 取答案 :当窗口长度达到 k 后,队首即为当前窗口最大值。
  • 为什么是 O(n) :每个下标最多入队一次、出队一次。

常见陷阱

  • 队列中存值而非下标 :无法判断元素是否已滑出窗口。必须存下标。
  • 入队前用 &lt; 而非 &lt;= :用 &lt; 会保留重复值,虽然结果正确但队列会变长。用 &lt;= 可弹出重复值,更紧凑。
  • 忘记弹出过期队首 :会导致最大值来自已滑出窗口的元素。
  • 用 max(nums[i:i+k]) 每次求最大值 :O(n · k),在 n = k = 10^5 时是 10^10,必然超时。
  • 用大顶堆但无法删除过期元素 :堆需要惰性删除(检查堆顶下标是否过期),实现比单调队列更繁琐。

参考实现

from collections import deque

class Solution:
    def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
        dq = deque()            # 存下标,其对应的值单调递减
        res = []
        for i, x in enumerate(nums):
            # 队尾比 x 小的都不可能成为最大值,弹出
            while dq and nums[dq[-1]] <= x:
                dq.pop()
            dq.append(i)
            # 队首已滑出窗口
            if dq[0] <= i - k:
                dq.popleft()
            if i >= k - 1:      # 窗口已满
                res.append(nums[dq[0]])
        return res