Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution
- {
- public:
- deque<pair<int,int> > dq;
- int cnt_added=0,cnt_removed=0;
- void add(int ele){
- while(!dq.empty() and dq.back().first<ele) dq.pop_back();
- dq.push_back({ele,cnt_added});
- cnt_added++;
- }
- void del(){
- if(!dq.empty() and dq.front().second==cnt_removed) dq.pop_front();
- cnt_removed++;
- }
- int mx(){
- return dq.front().first;
- }
- //Function to find maximum of each subarray of size k.
- vector <int> max_of_subarrays(int *arr, int n, int k)
- {
- // your code here
- for(int i=0;i<k;i++) add(arr[i]);
- vector<int>ans;
- ans.push_back(mx());
- for(int i=k;i<n;i++){
- del();
- add(arr[i]);
- ans.push_back(mx());
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement