单调栈的经典应用。找到左边最近的比它小的,找到右边的最近的比它小的。
#include<bits/stdc++.h>
using namespace std;
typedef long long int LL;
const int N=1e5+10;
LL h[N],lmin[N],rmin[N],n;
int main(void)
{
while(cin>>n,n)
{
for(int i=1;i<=n;i++) scanf("%lld",&h[i]);
h[0]=-1,h[n+1]=-1;
stack<int>st; st.push(0);
for(int i=1;i<=n;i++)
{
while(st.size()&&h[st.top()]>=h[i]) st.pop();
lmin[i]=st.top();
st.push(i);
}
while(st.size()) st.pop();
st.push(n+1);
for(int i=n;i>=1;i--)
{
while(st.size()&&h[st.top()]>=h[i]) st.pop();
rmin[i]=st.top();
st.push(i);
}
LL ans=0;
for(int i=1;i<=n;i++) ans=max(ans,(rmin[i]-lmin[i]-1)*h[i]);
cout<<ans<<endl;
}
return 0;
}