Wednesday, 14 December 2016

Largest Rectangular Area in a Histogram


/*
Tanzila Islam
Southeast University
mail: tanzilamohita@gmail.com
**/
#include <bits/stdc++.h>
using namespace std;
#define MX 100002

int hist[MX], lft[MX], rgt[MX];

//Largest Rectangular Area in a Histogram

void Histogram(int n)
{
    stack<int>stk;
    stk.push(0), hist[0]=-1;
    for(int i=1;i<=n;i++)
    {
        while(hist[stk.top()]>=hist[i])  stk.pop();
        lft[i]=  stk.top()+1, stk.push(i);
    }
    while(!stk.empty())   stk.pop();
    stk.push(n+1), hist[n+1]=-1;
    for(int i=n;i>0;i--)
    {
        while(hist[stk.top()]>=hist[i])   stk.pop();
        rgt[i]=  stk.top()-1, stk.push(i);
    }
return;
}

int main()
{
   int n;
   while(cin>>n && n)
   {
     for(int I=0;I<n;I++)
        cin>>hist[I];
     Histogram(n);

     int largestArea = 0;
     for(int I=0;I<n;I++)
        largestArea = max(largestArea, (rgt[I]-lft[I]+1)*hist[I]);
     cout<<largestArea<<endl;
   }
return 0;
}

No comments:

Post a Comment