代码随想录算法训练营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
相关推荐
WWZZ20251 天前
快速上手大模型:深度学习10(卷积神经网络2、模型训练实践、批量归一化)
人工智能·深度学习·神经网络·算法·机器人·大模型·具身智能
sali-tec1 天前
C# 基于halcon的视觉工作流-章62 点云采样
开发语言·图像处理·人工智能·算法·计算机视觉
fashion 道格1 天前
用 C 语言玩转归并排序:递归实现的深度解析
数据结构·算法·排序算法
九年义务漏网鲨鱼1 天前
蓝桥杯算法——状态压缩DP
算法·职场和发展·蓝桥杯
CappuccinoRose1 天前
MATLAB学习文档(二十八)
开发语言·学习·算法·matlab
Freedom_my1 天前
插入排序算法
数据结构·算法·排序算法
952361 天前
排序-算法
数据结构·算法·排序算法
WongKyunban1 天前
插入排序的原理和示例
数据结构·算法·排序算法
flashlight_hi1 天前
LeetCode 分类刷题:404. 左叶子之和
javascript·算法·leetcode
小白程序员成长日记1 天前
2025.11.19 力扣每日一题
算法·leetcode·职场和发展