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

leetcode: 84. Largest Rectangle in Histogram

作者头像
JNingWei
发布2018-09-27 17:02:54
5310
发布2018-09-27 17:02:54
举报

Problem

# 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].
这里写图片描述
这里写图片描述
# 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.

Idea

仔细考察Brute Force算法,发现问题在于指针重复扫描。以递增序列为例:

0 1 2 3 4 5 6

在计算s[0]的时候扫描了右边6个数,计算s[1]时继续扫描右边5个数,依次类推。而没能利用到这个序列的递增性质。当序列从i递增到j时,bar i~j的面积一定都能扩展到j。而一旦在j+1递减了,那么表示bar i~j中的部分bar k无法继续扩展,条件是h[k]>h[j+1]。

1. 利用这个性质,可以将递增序列cache在一个stack中,一旦遇到递减,则根据h[j+1]来依次从stack里pop出那些无法继续扩展的bar k,并计算面积。

2. 由于面积的计算需要同时知道高度和宽度,所以在stack中存储的是序列的坐标而不是高度。因为知道坐标后很容易就能知道高度,而反之则不行。

AC

class Solution():
    def largestRectangleArea(self, xs):
        xs.insert(0, 0)
        xs.append(0)
        stack, maxArea = [], 0
        for i, x in enumerate(xs):
            if not stack or xs[stack[-1]] <= x:
                stack.append(i)
            else:
                while stack and xs[stack[-1]] > x:
                    maxArea = max(maxArea, xs[stack[-1]]*(i-stack[-2]-1))
                    stack.pop()
                stack.append(i)
        right = stack[-1]
        stack.pop()
        while len(stack) > 1:
            offset = right-stack[-1]
            maxArea = max(maxArea, xs[stack[-1]]*offset)
            stack.pop()
        return maxArea


if __name__ == "__main__":
    assert Solution().largestRectangleArea([2, 0, 2]) == 2
    assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年11月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem
    • Idea
    • AC
    相关产品与服务
    对象存储
    对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档