Skip to content

Commit eb275d1

Browse files
committed
Added Solution - GfG to GitHub
1 parent afffc28 commit eb275d1

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
//{ Driver Code Starts
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
6+
// } Driver Code Ends
7+
8+
class Solution {
9+
public:
10+
vector<int> maxOfSubarrays(vector<int>& arr, int k) {
11+
vector<int>ans;
12+
deque<int>dq(k);
13+
for(int i=0; i<k; i++) {
14+
while(!dq.empty() && arr[i]>=arr[dq.back()]) {
15+
dq.pop_back();
16+
}
17+
dq.push_back(i);
18+
}
19+
for(int i=k; i<arr.size(); i++) {
20+
ans.push_back(arr[dq.front()]);
21+
while(!dq.empty() && dq.front()<=i-k) {
22+
dq.pop_front();
23+
}
24+
while(!dq.empty() && arr[i]>=arr[dq.back()]) {
25+
dq.pop_back();
26+
}
27+
dq.push_back(i);
28+
}
29+
ans.push_back(arr[dq.front()]);
30+
return ans;
31+
}
32+
};
33+
34+
35+
//{ Driver Code Starts.
36+
37+
int main() {
38+
int t;
39+
cin >> t;
40+
cin.ignore(); // Ignore newline character after t
41+
42+
while (t--) {
43+
vector<int> arr;
44+
int k;
45+
string inputLine;
46+
47+
getline(cin, inputLine); // Read the array input as a line
48+
stringstream ss(inputLine);
49+
int value;
50+
while (ss >> value) {
51+
arr.push_back(value);
52+
}
53+
54+
cin >> k;
55+
cin.ignore(); // Ignore newline character after k input
56+
57+
Solution obj;
58+
vector<int> res = obj.maxOfSubarrays(arr, k);
59+
for (int i = 0; i < res.size(); i++)
60+
cout << res[i] << " ";
61+
cout << endl;
62+
cout << "~"
63+
<< "\n";
64+
}
65+
66+
return 0;
67+
}
68+
69+
// } Driver Code Ends

0 commit comments

Comments
 (0)