class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<pair<int, int> > dq;
int n = nums.size();
vector<int> ans;
if (k <= 0 || k > n) {
return ans;
}
for (int i = 0; i < k - 1; ++i) {
while (!dq.empty() && dq.back().second <= nums[i]) {
dq.pop_back();
}
dq.push_back(make_pair(i, nums[i]));
}
for (int i = k - 1; i < n; ++i) {
//remove the useless element
while (!dq.empty() && dq.front().first + k <= i) {
dq.pop_front();
}
while (!dq.empty() && dq.back().second <= nums[i]) {
dq.pop_back();
}
dq.push_back(make_pair(i, nums[i]));
ans.push_back(dq.front().second);
}
return ans;
}
};