jayati

Maximum of minimum for every window size

Oct 10th, 2023
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  
  6. // } Driver Code Ends
  7.  
  8. class Solution
  9. {
  10.     public:
  11.     vector <int> maxOfMin(int arr[], int n)
  12.     {
  13.         stack<int> s;
  14.         vector<int> left(n), right(n);
  15.  
  16.         // Finding the nearest smaller element on the left
  17.         for (int i = 0; i < n; i++) {
  18.             while (!s.empty() && arr[s.top()] >= arr[i])
  19.                 s.pop();
  20.             left[i] = (s.empty()) ? 0 : s.top() + 1;
  21.             s.push(i);
  22.         }
  23.         for(int i=0;i<n;i++)
  24.         {
  25.             cout<<left[i]<<" ";
  26.         }
  27.         cout<<endl;
  28.         // Clearing the stack for the next round
  29.         while (!s.empty())
  30.         {
  31.              s.pop();
  32.         }
  33.            
  34.  
  35.         // Finding the nearest smaller element on the right
  36.         for (int i = n - 1; i >= 0; i--) {
  37.             while (!s.empty() && arr[s.top()] >= arr[i])
  38.                 s.pop();
  39.             right[i] = (s.empty()) ? n - 1 : s.top() - 1;
  40.             s.push(i);
  41.         }
  42.         for(int i=0;i<n;i++)
  43.         {
  44.             cout<<right[i]<<" ";
  45.         }
  46.         cout<<endl;        
  47.         vector<int> result(n);
  48.  
  49.         for (int i = 0; i < n; i++) {
  50.             int len = right[i] - left[i] + 1;
  51.             result[len - 1] = max(result[len - 1], arr[i]);
  52.         }
  53.  
  54.         // Filling in any gaps
  55.         for (int i = n - 2; i >= 0; i--) {
  56.             result[i] = max(result[i], result[i + 1]);
  57.         }
  58.  
  59.         return result;
  60.     }
  61. };
  62.  
  63.  
  64. //{ Driver Code Starts.
  65. int main() {
  66.     int t;
  67.     cin >> t;
  68.  
  69.     while (t--) {
  70.         int n;
  71.         cin >> n;
  72.         int a[n];
  73.         for (int i = 0; i < n; i++) cin >> a[i];
  74.         Solution ob;
  75.         vector <int> res = ob.maxOfMin(a, n);
  76.         for (int i : res) cout << i << " ";
  77.         cout << endl;
  78.     }
  79.     return 0;
  80. }
  81.  
  82. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment