Sliding Window Maximum in C++

C++Server Side ProgrammingProgramming

Suppose we have an array called nums, there is a sliding window of size k which is moving from the left of the array to the right. We can only see the k numbers in the window. Each time the sliding window moves to the right side by one position. We have to find the max sliding window. So if the input is like −[1,3,-1,-3,5,3,6,8] and k is 3, then the window will be like −

Window PositionMax
13-1-353683
13-1-353683
13-1-353683
13-1-353685
13-1-353686
13-1-353688

To solve this, we will follow these steps −

  • Define an array ans

  • Define one double ended queue dq

  • if size of nums is same as 0, then, return ans

  • for initializing i := 0, when i<k, increase i by 1 do −

    • while dq is not empty and nums[last element of dq] <nums[i], do

      • delete last element of dq

    • insert i at the end of dq

  • for initializing i := k, when i<nums.size(, increase i by 1 do −

    • insert (nums[front element of dq]) into ans

    • while dq is not empty and front element of dq < (i-k + 1), do −

      • delete front element from dq

    • while dq is not empty and nums[last element of dq] < nums[i], do −

      • delete last element of dq

    • insert i at the end of dq

  • insert nums[front element of dq] into ans at the end

  • return ans

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> maxSlidingWindow(vector<int>& nums, int k) {
      vector <int> ans;
      deque <int> dq;
      if(nums.size()==0)return ans;
      for(int i =0;i<k;i++){
         while(!dq.empty() && nums[dq.back()]<nums[i])dq.pop_back();
         dq.push_back(i);
      }
      for(int i = k;i<nums.size();i++){
         ans.push_back(nums[dq.front()]);
         while(!dq.empty() && dq.front()<(i-k + 1))dq.pop_front();
         while(!dq.empty() && nums[dq.back()]<nums[i])dq.pop_back();
         dq.push_back(i);
      }
      ans.push_back(nums[dq.front()]);
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,3,-1,-3,5,3,6,8};
   print_vector(ob.maxSlidingWindow(v,3));
}

Input

{1,3,-1,-3,5,3,6,8}

Output

[3, 3, 5, 5, 6, 8, ]
raja
Published on 27-May-2020 05:34:51
Advertisements