直方图最大矩形覆盖

给出的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;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值