代码随想录算法训练营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
相关推荐
平行侠12 分钟前
A19 工业设备故障决策树智能诊断系统
算法·决策树·机器学习
铮铭36 分钟前
【论文阅读】世界模型发展脉络整理---Understanding World or Predicting Future? A Comprehensive Survey of World Models
论文阅读·人工智能·算法·机器人
灵智实验室1 小时前
PX4状态估计技术EKF2详解(四):EKF2 Output Predictor——从延迟估计到实时输出
算法·无人机·px 4
科研小白_1 小时前
【MATLAB点云处理基础】基于区域生长算法的桥墩面域点云分割
算法
paeamecium1 小时前
【PAT甲级真题】- Shuffling Machine (20)
c++·算法·pat考试·pat
m0_737539371 小时前
pod Scheduler调度
算法·贪心算法
此生决int2 小时前
算法从入门到精通——双指针
算法
普马萨特2 小时前
Uber H3:地理网格索引在空间数据分析中的应用
数据结构·算法
alphaTao2 小时前
LeetCode 每日一题 2026/5/11-2026/5/17
算法·leetcode
洛水水2 小时前
【力扣100题】45.零钱兑换
算法·leetcode·职场和发展