求出 高度h[i]向左和向右最远能扩展到的下标
即利用单调栈 求出h[i]向左(右)最后一个不小于h[i]的下标
则以h[i]为高的面积为 h[i]*(R[i]-L[i]+1)
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;
const int N=1e6+20;
typedef long long ll;
ll h[N];
int L[N],R[N];//L[i] 高度h[i]向左最远能扩展到的下标
//则以h[i]为高的面积为 h[i]*(R[i]-L[i]+1)
int main()
{
int n;
while(cin>>n&&n)
{
stack <int> s;//单调栈 保存下标
for(int i=1;i<=n;i++)
{
scanf("%lld",&h[i]);
while(!s.empty()&&h[s.top()]>h[i])
{
R[s.top()]=i-1;//(i-1):h[s.top()]向右最后一个不小于于它的下标
s.pop();
}
s.push(i);
}
while(!s.empty())
{
R[s.top()]=n;
s.pop();
}
for(int i=n;i>=1;i--)
{
while(!s.empty()&&h[i]<h[s.top()])
{
L[s.top()]=i+1;
s.pop();
}
s.push(i);
}
while(!s.empty())
{
L[s.top()]=1;
s.pop();
}
ll ans=0;
for(int i=1;i<=n;i++)
{
ll res=(R[i]-L[i]+1)*h[i];
ans=max(res,ans);
}
cout<<ans<<endl;
}
return 0;
}