本题采用模仿栈的方式,先进后出,
最后记录一下我一开始不理解的地方,为什么是r[i] - l[i] - 1;因为一开始默认最右面是n + 1, 最左边是0,(例子:如果第一个点i它右边没有比它高的,那么它的r[i] = 2,左边l[i] = 0, 但它宽度只有1,所以这样算)
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n;
int h[N], l[N], r[N];
int top;
int stk[N];
int main()
{
while (scanf("%d", &n), n != 0)
{
for (int i = 1; i <= n; i ++ )
scanf("%d", &h[i]);
top = 0;
stk[++ top] = 0;
h[0] = h[n + 1] = -1;
for (int i = 1; i <= n; i ++ )
{
while (h[stk[top]] >= h[i]) top --;
l[i] = stk[top];
stk[++ top] = i;
}
top = 0;
stk[++ top] = n + 1;
for (int i = n; i >= 1; i -- )
{
while (h[stk[top]] >= h[i]) top --;
r[i] = stk[top];
stk[++ top] = i;
}
LL res = 0;
for (int i = 1; i <= n; i ++ )
res = max(res, (LL)h[i] * (r[i] - l[i] - 1));
cout << res << endl;
}
}