代码随想录算法训练营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
相关推荐
人间乄惊鸿客21 小时前
c++ 右值
c++·算法
fanstuck1 天前
AI 客服答错了,三分钟分清是 Prompt 还是系统的锅
算法
田里的水稻1 天前
FA_编程算法200个分类列数-SUM
算法·分类·数据挖掘
猿人谷1 天前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
地平线开发者1 天前
地平线 × 同济无人车队:PointPillars 从浮点模型到 BPU 部署
算法·自动驾驶
iiiiii111 天前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习
田里的水稻1 天前
FA_排序算法-冒泡排序
java·算法·排序算法
AAA修煤气灶刘哥1 天前
AI 写的 SQL 跑通了,为什么和财务报表对不上?
人工智能·后端·算法