代码随想录算法训练营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
相关推荐
圣保罗的大教堂16 小时前
leetcode 756. 金字塔转换矩阵 中等
leetcode
小尧嵌入式16 小时前
C++选择排序插入排序希尔排序快排归并排及大小根堆实现优先级队列
数据结构·c++·windows·算法·排序算法
Dream it possible!17 小时前
LeetCode 面试经典 150_分治_合并 K 个升序链表(108_23_C++_困难)
c++·leetcode·链表·面试·分治
天赐学c语言17 小时前
12.29 - 字符串相加 && vector和map的区别
数据结构·c++·算法·leecode
一招定胜负17 小时前
支持向量机实现垃圾邮件分类及参数调优原理
算法·支持向量机·分类
CodeByV17 小时前
【算法题】位运算
数据结构·算法
郝学胜-神的一滴17 小时前
李航《机器学习方法》全面解析与高效学习指南
人工智能·python·算法·机器学习·数学建模·scikit-learn
CS创新实验室17 小时前
奈奎斯特定理:信号处理与通信领域的基石理论
计算机网络·算法·信号处理·奈奎斯特定理
雪花desu17 小时前
【Hot100-Java简单】/LeetCode 283. 移动零:两种 Java 高效解法详解
数据结构·python·算法
随意起个昵称17 小时前
【做题总结】顺子(双指针)
c++·算法