# 239.sliding-window-maximum

## Statement

• Difficulty: Hard
• Tag: `队列` `数组` `滑动窗口` `单调队列` `堆（优先队列）`

``````输入：nums = [1,3,-1,-3,5,3,6,7], k = 3

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

``````输入：nums = [1], k = 1

``````

• `1 <= nums.length <= 105`
• `-104 <= nums[i] <= 104`
• `1 <= k <= nums.length`

• Difficulty: Hard
• Tag: `Queue` `Array` `Sliding Window` `Monotonic Queue` `Heap (Priority Queue)`

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

Constraints:

• `1 <= nums.length <= 105`
• `-104 <= nums[i] <= 104`
• `1 <= k <= nums.length`

## Solution

``````#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define endl "\n"
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall rbegin(a), rend(a)
#define bitcnt(x) (__builtin_popcountll(x))
#define complete_unique(a) a.erase(unique(begin(a), end(a)), end(a))
#define mst(x, a) memset(x, a, sizeof(x))
#define MP make_pair

using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using VLL = std::vector<ll>;
using VI = std::vector<int>;
using PII = std::pair<int, int>;
using PLL = std::pair<ll, ll>;

using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const ll mod = 1e9 + 7;

template <typename T, typename S>
inline bool chmax(T &a, const S &b) {
return a < b ? a = b, 1 : 0;
}

template <typename T, typename S>
inline bool chmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}

#ifdef LOCAL
#include <debug.hpp>
#else
#define dbg(...)
#endif

class Solution {
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k) {
auto res = vector<int>();
auto se = multiset<int>();

int n = nums.size();
for (int i = 0, j = 0; i < n; i++) {
se.insert(nums[i]);
if (se.size() == k) {
res.push_back(*(se.rbegin()));
se.erase(se.lower_bound(nums[j]));
++j;
}
}

return res;
}
};

#ifdef LOCAL

int main() {
return 0;
}

#endif
``````