-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsliding_window.cpp
49 lines (38 loc) · 1014 Bytes
/
sliding_window.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include<deque>
using namespace std;
int main() {
int n;
int a[100000];
int k;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
cin>>k;
//We have to process first k elements separtely
deque<int> Q(k);
int i;
for(i=0;i<k;i++){
while(!Q.empty() &&a[i]>a[Q.back()]){
Q.pop_back();
}
Q.push_back(i);
}
//Process the remaining elements
for(;i<n;i++){
cout<<a[Q.front()]<<" ";
//1. Remove the elements which are not the part of the window(Contraction)
while((!Q.empty() && (Q.front()<=i-k))){
Q.pop_front();
}
//2. Remove the elements which are not useful and are in window
while(!Q.empty() && a[i]>=a[Q.back()]){
Q.pop_back();
}
//3. Add the new elements(Expansion)
Q.push_back(i);
}
cout<<a[Q.front()]<<endl;
return 0;
}