代码随想录算法训练营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
相关推荐
郝学胜-神的一滴4 分钟前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_111 小时前
算法札记:有限差分
算法
忙里偷闲学python1 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农2 小时前
11.21程序设计
数据结构·算法
Tisfy2 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6172 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦3 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
Shaoshing4 小时前
LeetCode100 155.最小栈
java·数据结构·算法
秋天的怀念_David5 小时前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法