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

Leetcode-Hard 84. Largest Rectangle in Histogram

作者头像
致Great
发布2019-03-11 11:13:25
3170
发布2019-03-11 11:13:25
举报
文章被收录于专栏:程序生活程序生活

题目描述

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.

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

<small style="box-sizing: border-box; font-size: 12px;">The largest rectangle is shown in the shaded area, which has area = 10 unit.</small>

Example:

代码语言:javascript
复制
Input: [2,1,5,6,2,3]
Output: 10

思路

用栈来模拟,遍历heights数组,如果大于栈顶元素,就push进去;否则,持续弹栈来计算从栈顶点到降序点的矩阵大小。然后将这一部分全部替换为降序点的值,即做到了整体依然是有序非降的。 整个过程中,即把所有的局部最大矩阵计算过了,又在宽度范围内保留了全部的场景。

代码实现

代码语言:javascript
复制
class Solution:
    def largestRectangleArea(self, height):
        height.append(0)
        stack = [-1]
        ans = 0
        for i in range(len(height)):
            while height[i] < height[stack[-1]]:
                h = height[stack.pop()]
                w = i - stack[-1] - 1
                ans = max(ans, h * w)
            stack.append(i)
        height.pop()
        return ans
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.02.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路
  • 代码实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档