柱状图中的最大矩形(python)

思路:单调递增栈,遍历数组,入栈索引。

首先设置两个高度为0的柱子作为哨兵,前后各设置一个。使用一个单调递增栈,当栈不为空,且当前元素大于栈顶元素时,入栈。若当前元素小于栈顶元素时,说明找到了第一个比栈顶元素矮的元素,弹出一个栈顶元素,此时的栈顶元素就是左边界L,此时遍历到的元素就是右边界R,先前被弹出的元素就是高度H=heightsi,则此时矩阵面积为Area=H*(L-R-1)

复制代码
#柱状图中的最大矩形
import sys
from typing import List

def largestRectangleArea(h:List[int])->str:
    maxArea=0
    stack=[]
    for i in range(len(h)):
        while stack and h[i]<h[stack[-1]]:  #当前元素大于小于栈顶元素
            tmp=stack.pop()  #出栈
            a=h[tmp]  #柱子高度
            b=i-stack[-1]-1   #柱子宽度,i是右边界,stack[-1]是左边界
            maxArea=max(maxArea,a*b)
        stack.append(i)
    return maxArea
                   
def main():
    line=sys.stdin.readline().strip()
    if not line:
        return 0
    heights=list(map(int,line.split()))  #转换成数组
    h=[0]+heights+[0]   #前后拼接两个高度为0的柱子
    res=largestRectangleArea(h)
    print(res)
    return


if __name__=="__main__":
    main()
相关推荐
用户0332126663671 小时前
使用 Python 从零创建 Word 文档
python
Csvn6 小时前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽7 小时前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817538 小时前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱1 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei1 天前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi001 天前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn1 天前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵2 天前
[Python] 从《千字文》中随机挑选汉字
后端·python