-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMaximumOfSubArrayOfSizeK.cpp
49 lines (40 loc) · 1.2 KB
/
MaximumOfSubArrayOfSizeK.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 <bits/stdc++.h>
using namespace std;
vector<int> maxOfSubArrayOfSizeK(vector<int> &A, int k) {
int n = A.size();
deque<int> Qi(k);
vector<int> B;
int i;
for (i = 0; i < k; ++i) {
while ((!Qi.empty()) && A[i] >= A[Qi.back()])
Qi.pop_back();
Qi.push_back(i);
}
// Process rest of the elements, i.e., from A[k] to A[n-1]
for (; i < n; ++i) {
// The element at the front of the queue is the largest element of
// previous window, so print it
B.push_back(A[Qi.front()]);
// Remove the elements which are out of this window
while ((!Qi.empty()) && Qi.front() <= i - k)
Qi.pop_front(); // Remove from front of queue
// Remove all elements smaller than the currently
// being added element (remove useless elements)
while ((!Qi.empty()) && A[i] >= A[Qi.back()])
Qi.pop_back();
// Add current element at the rear of Qi
Qi.push_back(i);
}
// Print the maximum element of last window
B.push_back(A[Qi.front()]);
return B;
}
int main() {
vector<int> A{2, 1, 13, 87, 5, 12, 11, 43};
int k = 3;
vector<int> v2 = maxOfSubArrayOfSizeK(A, k);
for (int i = 0; i < v2.size(); i++) {
cout << v2[i] << ' ';
}
return 0;
}