代码随想录算法训练营Day60 | 单调栈(3/3) LeetCode 84.柱状图中最大的矩形

今天就是训练的最后一天了,刷满60天,感觉很有成就感!

84. Largest Rectangle in Histogram

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

用单调栈的思路来解这道题,本题是要找每个柱子左右两边第一个小于该柱子的柱子,所以从栈头(元素从栈头弹出)到栈底的顺序应该是从大到小的顺序。栈顶和栈顶的下一个元素以及要入栈的三个元素组成了我们要求最大面积的高度和宽度。

python 复制代码
class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        heights.insert(0, 0)
        heights.append(0)
        stack = [0]
        result = 0
        for i in range(1, len(heights)):
            while stack and heights[i] < heights[stack[-1]]:
                mid_height = heights[stack[-1]]
                stack.pop()
                if stack:
                    # area = width * height
                    area = (i - stack[-1] - 1) * mid_height
                    result = max(area, result)
            stack.append(i)
        return result
相关推荐
好记性+烂笔头9 分钟前
hot100_108. 将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
tt55555555555519 分钟前
每日一题——主持人调度(二)
c语言·数据结构·算法·leetcode·八股文
技术蔡蔡36 分钟前
Android字节码处理-函数耗时统计揭秘
算法·面试
Felven1 小时前
B. Skibidus and Ohio
算法
yonuyeung1 小时前
代码随想录算法【Day54】
java·数据结构·算法
敲上瘾1 小时前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
西猫雷婶1 小时前
python学智能算法(三)|模拟退火算法:深层分析
算法·机器学习·模拟退火算法
张有志_2 小时前
STL容器终极解剖:C++ vector源码级实现指南 | 从内存分配到异常安全的全流程避坑
c语言·c++·算法·开源·visual studio
mvufi2 小时前
day58 第十一章:图论part08
数据结构·算法·图论
williamzhou_20132 小时前
深搜专题2:组合问题
数据结构·算法