Idea: This
question is a typical question for sliding windows. The knowledge point used is monotonic queue (don't forget the knowledge point of monotonic stack). The value of the window is maintained through the double-ended queue to ensure that the head element of the window is in this interval The best value can be.
Code:
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> ans;
for(int i=0;i<nums.size();++i){
if(!dq.empty() && i-dq.front() >= k) dq.pop_front();
while(!dq.empty() && nums[dq.back()]<=nums[i]){
dq.pop_back();
}
dq.push_back(i);
if(i>=k-1) ans.push_back(nums[dq.front()]);
}
return ans;
}
};