直方图中最大的矩形

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100000 ;
using ll = long long ;
ll q[N],a[N];
int main()
{
    ios::sync_with_stdio(false);
    int n;
    while(cin>>n,n){
        for(int i=1;i<=n;i++) cin>>a[i];
        ll tot=0,ans=0;;
        a[n+1]=0;
        for(int i=1;i<=n+1;i++){
            while(tot&&a[q[tot]]>a[i]){
                ans=max(ans,(i-q[tot-1]-1)*a[q[tot]]);
                tot--;
            }
            q[++tot]=i;
        }
        cout<<ans<<"\n";
    }
}