> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/heap/239-sliding-window-maximum.md).

# 239 Sliding Window Maximum

## 239. [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/description/)

## 1. Question

Given an array 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.

For example,\
Givennums=`[1,3,-1,-3,5,3,6,7]`, andk= 3.

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

Therefore, return the max sliding window as`[3,3,5,5,6,7]`.

**Note:**\
You may assumekis always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

**Follow up:**\
Could you solve it in linear time?

## 2. Implementation

**(1) Heap with PriorityQueue**

```java
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        int n = nums.length;
        int[] res = new int[n - k + 1];
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

        for (int i = 0; i < n; i++) {
            maxHeap.add(nums[i]);

            if (i >= k) {
                maxHeap.remove(nums[i - k]);
            }

            if (i - k + 1 >= 0) {
                res[i - k + 1] = maxHeap.peek();
            }
        }
        return res;
    }
}
```

**(2) Heap with TreeMap**

```java
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        int n = nums.length;
        int[] res = new int[n - k + 1];

        TreeMap<Integer, Integer> map = new TreeMap();

        for (int i = 0; i < n; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);

            if (i >= k) {
                map.put(nums[i - k], map.get(nums[i - k]) - 1);
                if (map.get(nums[i - k]) == 0) {
                    map.remove(nums[i - k]);
                }
            }

            if (i - k + 1 >= 0) {
                res[i - k + 1] = map.lastKey();
            }
        }
        return res;
    }
}
```

**(3) Deque**

```java
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0) {
            return new int[0];
        }

        int n = nums.length;
        int[] res = new int[n - k + 1];

        ArrayDeque<Integer> deque = new ArrayDeque();
        int index = 0;

        for (int i = 0; i < n; i++) {
            // Remove index that is out of slinding window 
            while (!deque.isEmpty() && deque.peek() < (i - k + 1)) {
                deque.remove();
            }

            // Remove number which is smaller than the current number since they won't be the max
            while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
                deque.removeLast();
            }

            deque.add(i);

            if (i - k + 1 >= 0) {
                res[index++] = nums[deque.peek()];
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

**Heap with PriorityQueue:** 时间复杂度O(n\*k)，PriorityQueue.remove(Object)要O(k)的时间，而PriorityQueue.remove()需要O(logk)的时间, 空间复杂度O(n)\
**Heap with TreeMap:** 时间复杂度O(nlogk), 空间复杂度(n) TreeMap需要O(k)空间， res需要n - k + 1空间，加起来要O(n)

**Deque:** 时间复杂度O(n), 空间复杂度O(n)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/heap/239-sliding-window-maximum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
