-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSliding Window Maximum.cpp
More file actions
52 lines (44 loc) · 1.19 KB
/
Sliding Window Maximum.cpp
File metadata and controls
52 lines (44 loc) · 1.19 KB
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
50
51
52
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve() {
int t;
cin >> t;
while (t--) {
deque<int>dq;
vector<int > ans;
vector<int>v;
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v.push_back(x);
}
for (int i = 0; i < k; i++) {
while (!dq.empty() && dq.back() < v[i]) { /*Delete element from the deque until v[i] greater than dq back element.Thats means deque always maintail decreasing oder*/
dq.pop_back();
}
dq.push_back(v[i]);
}
ans.push_back(dq.front());
for (int i = k; i < n; i++) {
if (dq.front() == v[i - k]) { // if deque first element is no more in the window than delet that item//
dq.pop_front();
}
while (!dq.empty() && dq.back() < v[i]) {
dq.pop_back();
}
dq.push_back(v[i]);
ans.push_back(dq.front());
}
for (auto it : ans) {
cout << it << " ";
}
cout << endl;
}
}
int main() {
solve();
return 0;
}