Advertisement
srijan44

maxelementinwindow

Apr 6th, 2020
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void maxElement(int *arr,int n,int k){
  5.  
  6.     deque<int> q;
  7.  
  8.     int i=0;
  9.     for(i=0;i<k;i++){
  10.         while(!q.empty() && arr[i]>=arr[q.back()]){
  11.             q.pop_back();
  12.         }
  13.         q.push_back(i);
  14.     }
  15.     while(i<n){
  16.  
  17.         cout << arr[q.front()] << " ";
  18.         while(!q.empty() && q.front() <= i-k){
  19.             q.pop_front();
  20.         }
  21.         while(!q.empty() && arr[i]>=arr[q.back()]){
  22.             q.pop_back();
  23.         }
  24.         q.push_back(i);
  25.         i++;
  26.     }
  27.     cout << arr[q.front()] << endl;
  28.  
  29. }
  30.  
  31.  
  32. int main() {
  33.  
  34.     #ifndef ONLINE_JUDGE
  35.     // for getting input from input.txt
  36.     freopen("input.txt", "r", stdin);
  37.     // for writing output to output.txt
  38.     freopen("output.txt", "w", stdout);
  39.     #endif
  40.  
  41.     int n,k;
  42.     cin >> n >> k;
  43.  
  44.     int arr[n];
  45.    
  46.     for(int i=0;i<n;i++){
  47.         cin >> arr[i];
  48.     }
  49.  
  50.     maxElement(arr,n,k);
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement