-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrough.cpp
77 lines (55 loc) · 1.46 KB
/
rough.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <bits/stdc++.h>
using namespace std;
vector<int> findmax(vector<int>v,int K){
for(int left=0;left<v.size();left++){
int right=left+K-1;
if(right>=v.size()){
break;
}
int max=INT_MIN;
for(int i=left;i<=right;i++){
if(v[i]>max){
max=v[i];
}
}
v[left]=max;
}
vector<int>result(v.begin(),v.begin()+v.size()-K+1);
return result;
}
vector<int> findMax2(vector<int>& v, int K) {
deque<int> dq; // Deque to store indices of elements
vector<int> result; // Vector to store maximum values
for (int i = 0; i < v.size(); i++) {
// Remove indices outside the current window from deque's front
if (!dq.empty() && dq.front() < i - K + 1) {
dq.pop_front();
}
// Remove elements smaller than v[i] from deque's back
while (!dq.empty() && v[i] > v[dq.back()]) {
dq.pop_back();
}
// Add current index to deque
dq.push_back(i);
// Add maximum value for the current window to result
if (i >= K - 1) {
result.push_back(v[dq.front()]);
}
}
return result;
}
int main(){
int N,K;
K=3;
N=6;
vector<int>v={1,3,-1,-3,5,3};
vector<int>result=findmax(v,K);
for(int x:result){
cout<<x<<" ";
}
cout<<endl;
vector<int>result2=findMax2(v,K);
for(int x:result2){
cout<<x<<" ";
}
}