来了一个高度较小的长方形a,设a的左边有比a高的长方形b
将b pop()出来
则以b为高度的大长方形的宽度就能确定了
该长方形的右边界好确定,就是a所在的位置减一,因为a比b低,而在栈中,在b之前被pop()出来的的都比b高
左边界也好确定,就是当前栈顶的值加一,因为当前栈顶对应的高度是要小于b的高度的
栈中存放的是每个小长方形所在的位置,进而可以得出宽度
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <stack>
#include <cstdio>
using namespace std;
const int MAXN = int(1e5) + 5;
typedef long long ll;
int h[MAXN];
int main() {
int n;
while (scanf("%d", &n), n)
{
for (int i = 1; i <= n; ++i)
scanf("%d", h + i);
stack<int> s;
s.push(0);
h[++n] = 0;
h[0] = 0;
//维护一个递增的栈,存下标,也就是宽度
ll ans = 0;
for (int i = 1; i <= n; ++i)
{
while (h[i] < h[s.top()])
{
//当来了一个比栈顶低的,就把栈顶作为高,
//栈里的第二个元素的值加一为长方形的左端
//因为在这两个长方形之间,之前被pop的下标所对应的高度一定比s.top()对于的高度高或相等
//长方形的左边为pop后的s.top() + 1, 右边为i - 1
ll a = h[s.top()];
s.pop();
ll b = s.top() + 1;
ll t = a * (i - b);
ans = max(t, ans);
}
s.push(i);
}
printf("%lld\n", ans);
}
return 0;
}