
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sliding Window Maximum in C++
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 Position | Max | |||||||
---|---|---|---|---|---|---|---|---|
1 | 3 | -1 | -3 | 5 | 3 | 6 | 8 | 3 |
1 | 3 | -1 | -3 | 5 | 3 | 6 | 8 | 3 |
1 | 3 | -1 | -3 | 5 | 3 | 6 | 8 | 3 |
1 | 3 | -1 | -3 | 5 | 3 | 6 | 8 | 5 |
1 | 3 | -1 | -3 | 5 | 3 | 6 | 8 | 6 |
1 | 3 | -1 | -3 | 5 | 3 | 6 | 8 | 8 |
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 −
#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, ]