代码随想录算法训练营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
相关推荐
梦帮科技3 分钟前
多任务权重流形融合:SLERP 球形线性插值、DARE 稀疏剪枝与多专家模型融合落地
人工智能·深度学习·算法·机器学习·tensorflow·聚类·剪枝
Tisfy4 分钟前
LeetCode 0020.有效的括号:栈匹配
算法·leetcode·字符串·题解·括号匹配
测试学习test22 分钟前
SPI读取W25Q64硬件驱动(HAL库)
数据库·stm32·嵌入式硬件·算法
迅猛龙办公室29 分钟前
Python实现斐波那契数列
算法
淡海水31 分钟前
02-01-原理篇-Mark-Sweep与变种算法
算法·unity·c#·游戏引擎·.net·gc
Navigator_Z33 分钟前
LeetCode //C - 1276. Number of Burgers with No Waste of Ingredients
c语言·算法·leetcode
keyipatience1 小时前
跳表详细解析
开发语言·数据结构·c++·算法·跳表
想吃火锅10051 小时前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
大侠归来1 小时前
cJSON 源码解析:parse_string 函数深入剖析
linux·网络·算法
余额瞒着我当琳2 小时前
C++ map 底层与AVL 树
开发语言·c++·算法