Sliding window maximum
topic
Given an array nums, there is a sliding window of size k that moves from the far left of the array to the far right of the array. You can only see the k numbers in the sliding window. The sliding window moves only one position to the right at a time.
Returns the maximum value in the sliding window.
Advanced:
Can you solve this problem in linear time complexity?
Example:
Input: nums = [1,3, -1, -3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Maximum position of sliding window
[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
Run the code
class Solution {
public:
deque<int> dep;
void clean_queue(int idx,int i,vector<int>& nums){
if(!dep.empty()&&idx==dep.front())dep.pop_front();
while(!dep.empty()&&nums[dep.back()]<nums[i])dep.pop_back();
dep.push_back(i);
}
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
for(int i=0;i<k;i++){
clean_queue(i-k,i,nums);
}
res.push_back(nums[dep.front()]);
for(int i=k;i<nums.size();i++){
clean_queue(i-k,i,nums);
res.push_back(nums[dep.front()]);
}
return res;
}
};