代码随想录算法训练营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
相关推荐
mit6.82421 小时前
位运算|拆分贪心
算法
ghie909021 小时前
基于MATLAB的TLBO算法优化实现与改进
开发语言·算法·matlab
恋爱绝缘体121 小时前
2020重学C++重构你的C++知识体系
java·开发语言·c++·算法·junit
wuk99821 小时前
VSC优化算法MATLAB实现
开发语言·算法·matlab
Z1Jxxx1 天前
加密算法加密算法
开发语言·c++·算法
乌萨奇也要立志学C++1 天前
【洛谷】递归初阶 三道经典递归算法题(汉诺塔 / 占卜 DIY/FBI 树)详解
数据结构·c++·算法
vyuvyucd1 天前
C++引用:高效编程的别名利器
算法
鱼跃鹰飞1 天前
Leetcode1891:割绳子
数据结构·算法
️停云️1 天前
【滑动窗口与双指针】不定长滑动窗口
c++·算法·leetcode·剪枝·哈希
码农小韩1 天前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法