Maximum area rectangle in a Histogram

19 Dec 2019

Maximum area rectangle in a histogram

Problem

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 same width and the width is 1 unit.

Solution

Code

int maxAreaRectangle(vector<int> &A){
    int N=A.size();
    vector<int> lless(N, -1);
    vector<int> rless(N, N);
    int ans=0;
    stack<int> s;
    //s.push(-1);
    for(int i=0; i<N;i++){
        while(!s.empty() && A[s.top()]>=A[i]){
            rless[s.top()]=i;
            s.pop();
        }
        if(!s.empty()){
            lless[i]=s.top();
        }
        s.push(i);
    }
    while(!s.empty()){
        rless[s.top()]=N;
        s.pop();
    }
    
    for(int i=0; i<N; i++){
        int max = A[i]*(rless[i]-lless[i]-1);
        ans=(max>ans)?max:ans;
    }
    return ans;
}

P.S. -

Reference - geeksforgeeks

Take note