201312-3 最大的矩形

暴力做法:(O(n^2))

const int N=1010;
int a[N];
int l[N],r[N];
int n;

int main()
{
    cin>>n;

    for(int i=0;i<n;i++) cin>>a[i];

    int res=0;
    for(int i=0;i<n;i++)
    {
        int l=i,r=i;
        while(l>=0 && a[l] >= a[i])
            l--;
        while(r<n && a[r] >= a[i])
            r++;
        res=max(res,(r-l-1)*a[i]);
    }
    cout<<res<<endl;
    //system("pause");
    return 0;
}

单调栈做法:(O(n))

const int N=1010;
int a[N];
int l[N],r[N];
int stk[N],top;
int n;

int main()
{
    cin>>n;

    for(int i=0;i<n;i++) cin>>a[i];

    for(int i=0;i<n;i++)
    {
        while(top && a[stk[top]] >= a[i])
            top--;
        if(top) l[i]=stk[top]+1;
        else l[i]=0;
        stk[++top]=i;
    }

    top=0;
    for(int i=n-1;i>=0;i--)
    {
        while(top && a[stk[top]] >= a[i])
            top--;
        if(top) r[i]=stk[top]-1;
        else r[i]=n-1;
        stk[++top]=i;
    }

    int res=0;
    for(int i=0;i<n;i++)
        res=max(res,(r[i]-l[i]+1)*a[i]);
    cout<<res<<endl;

    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14501339.html