代码随想录算法训练营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
相关推荐
吃好睡好便好1 天前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
仰泳之鹅1 天前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
x_yeyue1 天前
三角形数
笔记·算法·数论·组合数学
念何架构之路1 天前
Go语言加密算法
数据结构·算法·哈希算法
AI科技星1 天前
《数学公理体系·第三部·数术几何》(2026 年版)
c语言·开发语言·线性代数·算法·矩阵·量子计算·agi
失去的青春---夕阳下的奔跑1 天前
560. 和为 K 的子数组
数据结构·算法·leetcode
黎阳之光1 天前
黎阳之光:以视频孪生重构智慧医院信息化,打造高标项目核心竞争力
大数据·人工智能·物联网·算法·数字孪生
丷丩1 天前
三级缓存下MVT地图瓦片服务性能优化策略
算法·缓存·性能优化·gis·geoai-up
m0_629494731 天前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
ʚ希希ɞ ྀ1 天前
单词拆分----dp
算法