-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslidingwindowmax.cpp
More file actions
48 lines (38 loc) · 972 Bytes
/
slidingwindowmax.cpp
File metadata and controls
48 lines (38 loc) · 972 Bytes
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
#include<bits/stdc++.h>
using namespace std;
queue<int>temp;
deque<int>maxNum;
vector<int> numbers;
void push(int idx) {
temp.push(idx);
while(!maxNum.empty() && numbers[idx] > numbers[maxNum.back()]) maxNum.pop_back();
maxNum.push_back(idx);
}
int getMax() {
return numbers[maxNum.front()];
}
void pop() {
if (temp.front() == maxNum.front()) maxNum.pop_front();
temp.pop();
}
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
numbers = nums;
vector <int> results;
for (int i = 0; i < k; i++) {
push(i);
}
results.push_back(getMax());
for (int i = k; i < nums.size(); i++) {
pop();
push(i);
results.push_back(getMax());
}
return results;
}
int main() {
vector <int> tes = {1,3,-1,-3,5,3,6,7};
vector<int> hasil = maxSlidingWindow(tes, 3);
for (int i = 0; i < hasil.size();i++) {
cout << hasil[i] << endl;
}
}