Largest Rectangle in a Histogram
Portal .
Title description
This question asks to find the largest rectangle in the histogram.
Input and output
Input
The input contains multiple sets of data. Each group of data contains one row, the first positive integer N indicates that there are N rectangles, and the next N positive integers describe its height. The data ends with N=0. Please refer to the English title for the data range.
Output
For each set of data, one line of output contains a positive integer, which represents the answer to that set of data.
Sample
Sample Input
7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0
Sample Output
8
4000
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
long long ans,h[N],t,q[N],n,l[N],r[N];
void get(long long b[N])
{
t=0,h[0]=-1;
for(int i=1;i<=n;i++)
{
while(h[q[t]]>=h[i]) t--;
b[i]=q[t];
q[++t]=i;
}
}
int main()
{
while(cin>>n)
{
if(n==0) return 0;
for(int i=1;i<=n;i++) cin>>h[i];
get(l);
reverse(h+1,h+1+n);
get(r);
ans=0;
for(int i=1,j=n;i<=n;i++,j--) ans=max(ans,h[i]*(n-l[j]-r[i]));
cout<<ans<<endl;
}
return 0;
}
After reading YXC's explanation, I have a great understanding .
Use the monotonic stack to find the left layer and the right layer, and find the first one on the left and the first one on the right to be smaller than it.
S=(right-left+1) *h.