单调栈内维护的信息是当前高度和以当前高度能够绘制矩形的长度。
思路:基于贪心的原理,我们希望以当前的高度能够画出更大的矩形。我们只要维护单调栈,即可获得当前高度向右边延展的最大长度。同时,向左边延展的长度保存在栈内,所以每次出栈的时候,我们都能更新答案。
代码:
#include <iostream>
using namespace std;
#define ll long long
const int maxn = 1e5+500;
ll height,n,sz,res,length;
pair<ll,ll> st[maxn];
int main(){
while(scanf("%d",&n)!=EOF&&n){
sz = res = 0;
for(int i=1;i<=n;i++){
length=0;
scanf("%lld",&height);
while(sz&&st[sz].first>=height){ //维护单调栈
res = max(res,st[sz].first*(st[sz].second+length)); //更新答案
length += st[sz--].second; //更新长度,同时出栈
}
st[++sz] = make_pair(height,length+1); //入栈
}
length = 0;
while(sz){
res = max(res,st[sz].first*(length+st[sz].second));
length += st[sz--].second;
}
printf("%lld\n",res);
}
return 0;
}