代码随想录算法训练营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
相关推荐
Ivanqhz2 小时前
php8 use-def链
算法·php
spter。2 小时前
AI 面试相同请求为什么会重复调用,如何解决
人工智能·面试·职场和发展
evans在进步3 小时前
LeetCode 189 轮转数组:三次反转原地解决,图解 Java 实现
java·算法·leetcode
歌_顿3 小时前
Drawing_To_Model
算法
龍德明宇3 小时前
AI不会疼-龍德明宇
人工智能·算法·大语言模型llm·负主体性·ai存在论
302wanger3 小时前
程序员写 SOP:把脑子里的流程固化下来
算法
科学实验家4 小时前
完全背包
算法
Smoothcloud润云4 小时前
GPU租赁数据安全怎么做?
人工智能·算法·ai·aigc·gpu算力·gpu
呜喵王阿尔萨斯4 小时前
extern “C“ in C++
c语言·c++·算法