Maximum Rectangular Area in a Histogram | Practice | GeeksforGeeks

Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have the same width and the width is 1 unit, there will be N bars height of each bar will be given by the array arr.
Example 1:
Input:
N = 7
arr[] = {6,2,5,4,5,1,6}
Output: 12
Explanation: 



Example 2:
Input:
N = 8
arr[] = {7 2 8 9 1 3 6 5}
Output: 16
Explanation: Maximum size of the histogram 
will be 8  and there will be 2 consecutive 
histogram. And hence the area of the 
histogram will be 8x2 = 16.
Your Task:
The task is to complete the function getMaxArea() which takes the array arr[] and its size N as inputs and finds the largest rectangular area possible and returns the answer.
Expected Time Complxity : O(N)
Expected Auxilliary Space : O(N)
Constraints:
1 ≤ N ≤ 106
1 ≤ arr[i] ≤ 1012
0
godvishalkumar7861 hour ago
 
//java solutions 
 public static long getMaxArea(long heights[], long m)    {       // your code here      // int n= heights.length;      int n= heights.length;       int []right= new int [n];         Stack<Integer> st= new Stack<>();       st.push(n-1);       right[n-1]=n;       for(int i=n-2; i>=0; i--){           while(st.size() > 0 && heights[i] <= heights[st.peek()]){               st.pop();           }           if(st.size()==0){               right[i]=n;           }           else{               right[i]=st.peek();           }           st.push(i);       }       st.clear();              int []left= new int[n];      // Stack<Integer> st= new Stack<>();       st.push(0);       left[0]=-1;       for(int i=1; i<n; i++){           while(st.size() > 0 && heights[i] <= heights[st.peek()]){               st.pop();           }           if(st.size()==0){               left[i]=-1;           }           else{               left[i]=st.peek();           }           st.push(i);       }                     long Max=0;       for(int i=0; i<heights.length; i++){           int width= right[i]-left[i]-1;           long area= heights[i]*width;           Max= Math.max(area,Max);       }      return Max;   }   }
0
singh3003661 day ago
arr[in]*(nearest smaller to right -nearest smaller to left -1) 
class Solution
{
    public:
    //Function to find largest rectangular area possible in a given histogram.
    long long getMaxArea(long long arr[], int n)
    {
        // Your code here
        long long mx= -1;
        stack<pair<long long,long long>> st;
        stack<pair<long long,long long>> st1;
        vector<long long > nsl;
        vector<long long > nsr;
        vector<long long > ans;
        //nearest greater to left
        for(int i=0;i<n;i++){
            if(st.size()==0)
                nsl.push_back(-1);
            else if(st.size()>0 and st.top().first < arr[i])
                nsl.push_back(st.top().second);
            else if(st.size() >0  and st.top().first >= arr[i]){
                
                while(st.size() >0 and st.top().first >= arr[i])
                    st.pop();
                if(st.size()==0)
                    nsl.push_back(-1);
                else
                    nsl.push_back(st.top().second);
            }
            st.push({arr[i], i});
        }

        //nearest greater to right
        for(int i=n-1;i>=0;i--){
            if(st1.size()==0)
                nsr.push_back(n);
            else if(st1.size()>0 and st1.top().first < arr[i])
                nsr.push_back(st1.top().second);
            else if(st1.size() >0  and st1.top().first >= arr[i]){
                
                while(st1.size() >0 and st1.top().first >= arr[i])
                    st1.pop();
                if(st1.size()==0)
                    nsr.push_back(n);
                else
                    nsr.push_back(st1.top().second);
            }
            st1.push({arr[i], i});
        }
        
        reverse(nsr.begin(), nsr.end());
        
        
        for(int i=0;i<n;i++){
            mx= max(arr[i]*(nsr[i]-nsl[i]-1),mx);
        }
        return mx;
    }
};
0
mahesh_phutane4 days ago
simple java solution
class Solution
{
    //Function to find largest rectangular area possible in a given histogram.
    public static long getMaxArea(long hist[], long n) 
    {
        //brute force solution
        long maxArea = 0;
        if(n==1){
            return hist[0];
        }
        Stack<Integer> st = new Stack<>();
        int[] nsi = new int[(int)n];
        int[] psi = new int[(int)n];
        Arrays.fill(nsi,(int)n);
        Arrays.fill(psi,-1);
        for(int i = 0;i<n;i++){
            while(!st.empty() && hist[st.peek()]>hist[i]){
                nsi[st.peek()] = i;
                st.pop();
            }
            st.push(i);
        }
        
        while(!st.empty()){
            st.pop();
        }
        
        for(int i = (int)n-1;i>=0;i--){
            while(!st.empty() && hist[st.peek()]>hist[i]){
                psi[st.peek()] = i;
                st.pop();
            }
            st.push(i);
        }
        
        for(int i = 0;i<n;i++){
            maxArea = Math.max(maxArea,hist[i]*(nsi[i]-psi[i]-1));
        }
        
        return maxArea;
    }
        
}
0
putyavka1 week ago
long long getMaxArea(long long arr[], int n)
{
    stack<int> S;
    long long area = 0;
    for (int i = 0; i <= n; i++) {
        auto v = i < n ? arr[i] : 0;
        while (S.size() && arr[S.top()] >= v) {
            auto j = S.top(); S.pop();
            auto k = S.size() ? S.top() : -1;
            area = max(area, arr[j] * (i - k - 1));
        }
        S.push(i);
    }
    return area;
}
0
shilsoumyadip2 weeks ago
 long long getMaxArea(long long arr[], int n)   {       // Your code here       stack<int>st;       long long maxi = 0;       long long ans = 0;       long long i = 0;              while(i<n)       {           if(st.empty() or arr[i] >= arr[st.top()])           {               st.push(i);               i++;           }           else           {               long long t = st.top();               st.pop();                              ans = arr[t] * (st.empty() ? i : i - st.top() - 1 );                              maxi = max(maxi , ans);           }       }       while(!st.empty())       {            long long t = st.top();               st.pop();                              ans = arr[t] * (st.empty() ? i : i - st.top() - 1 );                              maxi = max(maxi , ans);       }       return maxi;   }
0
nooobcodder1 month ago
Getting segmentation fault on 40th testcase why??
long long getMaxArea(long long arr[], int n)
    {
        // Your code here
        int pre[n];
        int post[n];
        pre[0]=-1;
        stack<int> s;
        s.push(0);
        for(int i=1;i<n;i++){
            while(!s.empty()&&arr[i]<=arr[s.top()]){
                s.pop();
            }
            if(s.empty()) pre[i]=-1;
            else pre[i]=s.top();
            s.push(i);
        }
        
        while(!s.empty()) s.pop();
        
        post[n-1]=n;
        s.push(n-1);
        
        for(int i=n-2;i>=0;i--){
            while(!s.empty()&&arr[i]<=arr[s.top()]){
                s.pop();
            }
            if(s.empty()) post[i]=n;
            else post[i]=s.top();
            s.push(i);
        }
        long long maxArea=0;
        for(int i=0;i<n;i++){
            maxArea=max((post[i]-pre[i]-1)*arr[i],maxArea);
            
        }
        return maxArea;
    }
0
tarunkanade1 month ago
1.2/2.5
public static long getMaxArea(long hist[], long n) 
    {
        // your code here
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        long res = 0, curr = 0;
        
        for(int i = 0; i < n; i++){
            while(!stack.isEmpty() && hist[stack.peek()] >= hist[i]){
                int top = stack.pop();
                
                curr = hist[top] * ((stack.isEmpty()) ? i : (i - stack.peek() - 1));
                res = Math.max(curr, res);
            }
            
            stack.push(i);
        }
        
        while(!stack.isEmpty()){
            int top = stack.pop();
            
            curr = hist[top] * ((stack.isEmpty()) ? n : (n - stack.peek() - 1));
            res = Math.max(curr, res);
        }
        return res;
    }
0
amarrajsmart1971 month ago
C++ Solution Using Stack
Time Taken =0.5/2.2 Sec.
long long i=0;       long long max_=INT_MIN;       long long area;       stack<long long> st;       while(i<n)       {           if(st.empty()||arr[st.top()]<=arr[i])           {               st.push(i++);           }           else           {                long long tp=st.top();               st.pop();                area=arr[tp]*(st.empty()?i:i-st.top()-1);               max_=max(max_,area);           }       }       while(!st.empty())       {             long long tp=st.top();               st.pop();                area=arr[tp]*(st.empty()?i:i-st.top()-1);               max_=max(max_,area);       }       return max_;
0
banson1 month ago
//C++
vector<long long> nextLargerElement(long long arr[], int n)      {       // Your code here       vector<long long>ans;       stack<long long>s;       s.push(n-1);       ans.push_back(n);       for(int i=n-2;i>=0;i--)       {           while(!s.empty() && arr[s.top()]>=arr[i])           {               s.pop();           }           if(!s.empty())           {               ans.push_back(s.top());           }           else           {               ans.push_back(n);           }           s.push(i);       }       reverse(ans.begin(),ans.end());       return ans;   }      vector<long long> previousgreaterElement(long long arr[], int n)      {       // Your code here       vector<long long>ans;       stack<long long>s;       s.push(0);       ans.push_back(-1);       for(int i=1;i<n;i++)       {           while(!s.empty() && arr[s.top()]>=arr[i])           {               s.pop();           }           if(!s.empty())           {               ans.push_back(s.top());           }           else           {               ans.push_back(-1);           }           s.push(i);       }      // reverse(ans.begin(),ans.end());       return ans;   }      long long getMaxArea(long long arr[], int n)   {       // Your code here       //vector<long long>arr(n);       vector<long long>ps= previousgreaterElement(arr,n);       vector<long long>ns= nextLargerElement(arr,n);       long long res=0;              for(int i=0;i<n;i++)       {           long long curr=arr[i];           curr+=(i-ps[i]-1)*arr[i];           curr+=(ns[i]-i-1)*arr[i];           res=max(res,curr);       }              return res;   }
0
anubhavnegi541 month ago
Java || 1 pass solution || using StacksTime complexity : O(2n)  ( linear traversal + pushing elements inside stack)
Note : Deletion from stack does not happen for all elements 
Space complexity : O(n) ( storing items in stack) 
 
          Stack<Integer> s = new Stack<>();
        

        long maxArea = 0;
        for (int i = 0; i <= (int)n; i++) {
            while (!s.isEmpty() && (i == n || hist[i] <= hist[s.peek()])) {
                long height = hist[s.peek()];
                s.pop();
                long width;
                if (s.isEmpty()) {
                    width = i;
                } else {
                    width = i - s.peek() - 1;
                }

                maxArea = Math.max(maxArea, height * width);

            }
            s.push(i);
        }
        return maxArea;
    }  
Remark : I feel to understand this code is a bit tough so do a lot of dry runs. 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.