Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
689 views
in Online Assessments by Expert (108,690 points) | 689 views

2 Answers

0 like 0 dislike
Best answer

image
Can anyone please solve this?

by Expert (108,690 points)
0 like 0 dislike
#include<bits/stdc++.h>
using namespace std;

int largestSquareSide(vector<int>& a) {
    int n = a.size();
    stack<int>st; 
    vector<int>left(n,0), right(n,0);
    for(int i=0;i<n;i++){
        while(st.size() && a[st.top()]>=a[i]){
            st.pop();
        }
        if(st.size()){
            left[i] = st.top();
        }else{
            left[i] = -1;
        }
        st.push(i);
    }
    while(st.size()){st.pop();}
    for(int i=n-1;i>=0;i--){
        while(st.size() && a[st.top()]>=a[i]){
            st.pop();
        }
        if(st.size()){
            right[i] = st.top();
        }else{
            right[i] = n;
        }
        st.push(i);
    }
    while(st.size()){st.pop();}
    int ans = 0;
    for(int i=0;i<n;i++){
        int mini = min(a[i] , right[i]-left[i]-1);
        ans = max(ans,mini);
    }
    return ans;
}

signed  main(){
	int n;
    cin>>n;
    vector<int>a(n);
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    cout<<largestSquareSide(a)<<endl;
    return 0;
}

 

monotonic stack will work
similar to https://leetcode.com/problems/container-with-most-water/

by Expert (108,690 points)