直方图内最大矩形:用栈实现一些之前可以确定的值。

来源:互联网 发布:足球球员数据统计表格 编辑:程序博客网 时间:2024/06/07 04:00

题目描述

有一个直方图,用一个整数数组表示,其中每列的宽度为1,求所给直方图包含的最大矩形面积。比如,对于直方图[2,7,9,4],它所包含的最大矩形的面积为14(即[7,9]包涵的7x2的矩形)。

给定一个直方图A及它的总宽度n,请返回最大矩形面积。保证直方图宽度小于等于500。保证结果在int范围内。

测试样例:
[2,7,9,4,1],5

返回:14


思路:用栈实现一些之前可以确定的值。


struct Rect{    int height;    int width;};/*    以[2,7,9,4,1]为例,当遍历到4时,代表7,9所生成的面积已经可以完全确定。所以这题可以用栈实现,且时间为O(n)*/class MaxInnerRec {public:    int countArea(vector<int> A, int n) {        stack<Rect> st;        A.push_back(0);        int maxs=0;        for (int i = 0; i < n+1; ++i)        {            Rect node;            Rect cur;            node.height=A[i];            node.width=1;            int lastwidth=0;            while(!st.empty()&&st.top().height>A[i]){//栈中比当前A[i]大的所有可产生的矩形面积均可确定。                cur=st.top();                st.pop();                cur.width+=lastwidth;                lastwidth=cur.width;                int s=cur.height*cur.width;                if(s>maxs)                      maxs=s;            }            node.width+=lastwidth;            st.push(node);        }        return maxs;    }};


0 0
原创粉丝点击