Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include <bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- class Solution
- {
- public:
- vector <int> maxOfMin(int arr[], int n)
- {
- stack<int> s;
- vector<int> left(n), right(n);
- // Finding the nearest smaller element on the left
- for (int i = 0; i < n; i++) {
- while (!s.empty() && arr[s.top()] >= arr[i])
- s.pop();
- left[i] = (s.empty()) ? 0 : s.top() + 1;
- s.push(i);
- }
- for(int i=0;i<n;i++)
- {
- cout<<left[i]<<" ";
- }
- cout<<endl;
- // Clearing the stack for the next round
- while (!s.empty())
- {
- s.pop();
- }
- // Finding the nearest smaller element on the right
- for (int i = n - 1; i >= 0; i--) {
- while (!s.empty() && arr[s.top()] >= arr[i])
- s.pop();
- right[i] = (s.empty()) ? n - 1 : s.top() - 1;
- s.push(i);
- }
- for(int i=0;i<n;i++)
- {
- cout<<right[i]<<" ";
- }
- cout<<endl;
- vector<int> result(n);
- for (int i = 0; i < n; i++) {
- int len = right[i] - left[i] + 1;
- result[len - 1] = max(result[len - 1], arr[i]);
- }
- // Filling in any gaps
- for (int i = n - 2; i >= 0; i--) {
- result[i] = max(result[i], result[i + 1]);
- }
- return result;
- }
- };
- //{ Driver Code Starts.
- int main() {
- int t;
- cin >> t;
- while (t--) {
- int n;
- cin >> n;
- int a[n];
- for (int i = 0; i < n; i++) cin >> a[i];
- Solution ob;
- vector <int> res = ob.maxOfMin(a, n);
- for (int i : res) cout << i << " ";
- cout << endl;
- }
- return 0;
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment