239. Sliding Window Maximum
Hard NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Sliding Window
- Time
- O(N)
- Space
- O(K)
A standard reference solution for this problem is coming soon.
My Solution (C++)
#include <vector>
#include <deque>
using namespace std;
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
// use monotonic deque
// the idea is to maintain a deque in decrease order
// the deque size is at most k
// in each iteration:
// 1. remove the expired number from the front (if exist)
// 2. start from the back, remove all values smaller than the current value
// 3. insert the current value
// 4. read the max from the front
// note: in dq, store index instead value
deque<int> dq;
vector<int> ans;
int n=nums.size();
ans.reserve(n+k-1);
for(int i=0; i<n; ++i){
// 1.
if(!dq.empty() && i-dq.front()>=k){
dq.pop_front();
}
// 2.
while(!dq.empty() && nums[dq.back()]<nums[i]){
dq.pop_back();
}
// 3.
dq.push_back(i);
// 4.
if(i>=k-1){
ans.push_back(nums[dq.front()]);
}
}
return ans;
}
};
// Time Complexity: O(N), the pop_back() and pop_front() are amortized O(1) since each index is pushed and popped at most once
// Space Complexity: O(K) Time O(N) Space O(K)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.