前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0084 - Largest Rectangle in Histogram

LeetCode 0084 - Largest Rectangle in Histogram

作者头像
Reck Zhang
发布2021-08-11 10:49:46
1940
发布2021-08-11 10:49:46
举报
文章被收录于专栏:Reck ZhangReck Zhang

Largest Rectangle in Histogram

Desicription

Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

fuck
fuck

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

fuck
fuck

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,

Given heights = [2,1,5,6,2,3],

return 10.

Solution

代码语言:javascript
复制
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<pair<int, int>> s;
        int res = 0;
        for (int i = 0; i < heights.size(); i++) {
            if (s.empty() || s.top().first < heights[i])
                s.push(make_pair(heights[i], 1));
            else {
                int pre_weight = 0;
                while (s.size() && s.top().first >= heights[i]) {
                    pair<int, int> cur = s.top();
                    s.pop();
                    res = max(res, cur.first * cur.second);
                    if (s.size() && s.top().first >= heights[i])
                        s.top().second += cur.second;
                    pre_weight = cur.second;
                }
                s.push(make_pair(heights[i], 1 + pre_weight));
            }
        }
        while (s.size()) {
            pair<int, int> cur = s.top();
            s.pop();
            if (s.size())
                s.top().second += cur.second;
            res = max(res, cur.first * cur.second);
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-11-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Largest Rectangle in Histogram
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档