直方图最大矩形覆盖

 

链接:LintCode 炼码 - ChatGPT!更高效的学习体验!

题解:这是一个单调递增栈,弹出的元素保证,从当前位置向后扫,能构成矩形

九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧

class Solution {
public:
    /**
     * @param heights: A list of integer
     * @return: The area of largest rectangle in the histogram
     */
    int largestRectangleArea(vector<int> &heights) {
        // write your code here
        if (heights.size() <= 0) {
            return 0;
        }
        std::stack<int> sta;
        int result = 0;
        for (int i = 0; i <= heights.size(); ++i) {
            int cur_height = i == heights.size() ? -1 : heights[i];
            while (!sta.empty() && cur_height <= heights[sta.top()]) {
                int top = sta.top();
                sta.pop();
                int h = heights[top];
                int w = sta.empty() ? i : i - sta.top() - 1;
                result = max(result, h * w);
            }
            sta.push(i);
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值