Use the a deque to save numbers like a waitlist. If the window size equals to k, start the pop operation of the deque and push the front number into the res vector. If nums[i-k] equals to the front number of deque, the front should be popped because the window moves. Then a new number nums[i] should be pushed from back of the deque. While pushing, all numbers at the back of the deque which are smaller than nums[i] should be removed because they came earlier than nums[i] and if they are moved out of the window later, all numbers that are bigger than them are still in the deque, so the maximum number won't be affected.
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
deque<int> waitlist;
int n=nums.size();
int i=0;
while(i<n)
{
if(i>=k&&nums[i-k]==waitlist.front())
waitlist.pop_front();
while(!waitlist.empty()&&nums[i]>waitlist.back())
waitlist.pop_back();
waitlist.push_back(nums[i]);
i++;
if(i>=k)
res.push_back(waitlist.front());
}
return res;
}
};