直方图最大矩形覆盖

来源:互联网 发布:制作相册影集的软件 编辑:程序博客网 时间:2024/05/17 07:41

给出的n个非负整数表示每个直方图的高度,每个直方图的宽均为1,在直方图中找到最大的矩形面积。


以上直方图宽为1,高度为[2,1,5,6,2,3]


最大矩形面积如图阴影部分所示,含有10单位

样例

给出 height = [2,1,5,6,2,3],返回10

struct Value{    Value(int a, int b)    {        x = a;        y = b;    }    int x;    int y;};class Solution {public:    /**     * @param height: A list of integer     * @return: The area of largest rectangle in the histogram     */    int largestRectangleArea(vector<int> &height) {        // write your code here        int n = height.size();        if (n < 1)        {            return 0;        }        stack<Value> buf;        int result = 0;        height.push_back(0);        for (int i = 0; i <= n; i++)        {            if (height[i] == 0)            {                while (!buf.empty())                {                    Value top = buf.top();                    int temp = (i - top.x) * top.y;                    if (temp > result)                    {                        result = temp;                    }                    buf.pop();                }            }            else if (buf.empty())            {                buf.push(Value(i, height[i]));            }            else            {                Value top = buf.top();                if (height[i] > top.y)                {                    buf.push(Value(i, height[i]));                }                else if (height[i] < top.y)                {                    int x = top.x;                    while (!buf.empty() && height[i] < top.y)                    {                        x = top.x;                        int temp = (i - top.x) * top.y;                        if (temp > result)                        {                            result = temp;                        }                        buf.pop();                        if (!buf.empty())                        {                            top = buf.top();                        }                    }                    if (buf.empty() || height[i] > top.y)                    {                        buf.push(Value(x, height[i]));                    }                }            }        }        return result;    }};


0 0
原创粉丝点击