求柱状图中最大的矩形

问题:

# 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 
#
# 求在该柱状图中,能够勾勒出来的矩形的最大面积。

方法一:暴力

复制代码
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        length = len(heights)
        max_area = 0
        for i in range(length):
            min_height = math.inf
            for j in range(i, length):
                min_height = min(min_height, heights[j])
                area = min_height * (j-i+1)
                max_area = max(area, max_area)
        return max_area
# leetcode submit region end(Prohibit modification and deletion)
复制代码

方法二:优化,遍历每个柱子,左右扩展找满足条件的左柱和右柱

复制代码
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        length = len(heights)
        max_area = 0
        for i in range(length):
            current_height = heights[i]
            left = right = i
            while (left-1 >= 0 and heights[left-1] >= current_height):
                left -= 1
            while (right+1 < length and heights[right+1] >= current_height):
                right += 1
            max_area = max(max_area, (right-left+1) * current_height)
        return max_area
# leetcode submit region end(Prohibit modification and deletion)
复制代码

 方法三:维护一个单调栈,向左右寻找首次小于当前元素值的柱子索引

复制代码
heights = [2,1,5,6,2,3]
def largestRectangeArea(heights):
    heights = [0] + heights + [0]   # 前后插入零,处理剩余情况
    stack = []
    area = 0
    for i in range(len(heights)):  # 遍历柱子,计算该索引前一个柱子可能的最大面积
        while stack and heights[stack[-1]] > heights[i]:    # 栈不空且遍历到柱子小于栈顶元素,可以计算面积了
            cur = stack.pop()
            area = max(area, heights[cur]*(i-1-stack[-1]))  # 宽度是前一个柱子到单调栈栈顶元素的距离
        stack.append(i)
    return area
print(largestRectangeArea(heights))
复制代码

参考:https://juejin.cn/post/6859710267346026510

https://cloud.tencent.com/developer/article/1595001

posted @   今夜无风  阅读(71)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示