-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathK_Sized_Sub_array_Maximum.cpp
75 lines (58 loc) · 1.62 KB
/
K_Sized_Sub_array_Maximum.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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution {
public:
// Function to find maximum of each subarray of size k.
vector<int> max_of_subarrays(int k, vector<int> &arr) {
int i;
vector<int> ans;
deque<int> dq(k);
for(i = 0; i < k; i++)
{
while(!dq.empty() && arr[i] >= arr[dq.back()])
dq.pop_back();
dq.push_back(i);
}
for(;i < arr.size(); i++)
{
ans.push_back(arr[dq.front()]);
while(!dq.empty() && dq.front() <= i - k)
dq.pop_front();
while(!dq.empty() && arr[i] >= arr[dq.back()])
dq.pop_back();
dq.push_back(i);
}
ans.push_back(arr[dq.front()]);
return ans;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
string ks;
getline(cin, ks);
int k = stoi(ks);
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution obj;
vector<int> res = obj.max_of_subarrays(k, arr);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends