题目分析
首先需要找到最左边以及最右边比h[i]大的位置,这样结果就很容易算出来,ans = h[i]*(r[i]-l[i]+1);但是求l[i]以及r[i]如果不进行优化的话会直接超时,因此我们可以利用前面所求的l[0….i-1]来更快的得到l[i],本题的难点也在这。自己拿手对着代码推一遍你就会理解了,详细的请看代码。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 100005;
LL l[maxn],r[maxn],h[maxn];
int main()
{
int n;
while(scanf("%d", &n) != EOF && n)
{
for(int i = 1; i <= n; i++)
scanf("%I64d", &h[i]);
l[1] = 1;
for(int i = 2; i <= n; i++)
{
int t = i;
while(t > 1 && h[t-1] >= h[i])
t = l[t-1];
l[i] = t;
}
r[n] = n;
for(int i = n-1; i >= 1; i--)
{
int t = i;
while(t < n && h[t+1] >= h[i])
t = r[t+1];
r[i] = t;
}
LL ans = 0;
for(int i = 1; i <= n; i++)
ans = max(ans, h[i]*(r[i]-l[i]+1));
printf("%I64d\n", ans);
}
return 0;
}