【LeetCode热题100(99/100)】柱状图中最大的矩形

题目地址: 链接

根据题目易知,想要形成矩形,至少有一个值是完全使用的,所以可以利用单调栈记录每个值的可扩善(左右任意一侧)的最远距离。

最终,根据每个值最远可扩善距离 * height[i],循环比较完毕后即可获取最大矩形面积

TS 复制代码
function largestRectangleArea(heights: number[]): number {
    const n = heights.length;
    
    const dpLeft = new Array(n).fill(0);
    const dpRight= new Array(n).fill(0);

    const stk = [];
    for(let i = 0; i < n; i ++) {
        let [num, idx] = [0, -1];
        while(stk.length && stk[stk.length - 1][0] >= heights[i]) {
            [num, idx] = stk.pop();
        }
        if(stk.length === 0) dpLeft[i] = i;
        else dpLeft[i] = i - stk[stk.length - 1][1] - 1;
        stk.push([heights[i], i]); 
    }


    let ans = 0;
    stk.length = 0;
    for(let i = n - 1; i >= 0; i --) {
        let [num, idx] = [0, n];
        while(stk.length && stk[stk.length - 1][0] >= heights[i]) {
            [num, idx] = stk.pop();
        }
        if(stk.length === 0) dpRight[i] = n - i - 1;
        else dpRight[i] = stk[stk.length - 1][1] - i - 1;
        stk.push([heights[i], i]); 

        ans = Math.max((dpLeft[i] + dpRight[i] + 1) * heights[i], ans);
    }

    return ans;
};
相关推荐
啊阿狸不会拉杆2 小时前
《机器学习导论》第 9 章-决策树
人工智能·python·算法·决策树·机器学习·数据挖掘·剪枝
Mr_Xuhhh2 小时前
C++11实现线程池
开发语言·c++·算法
若水不如远方2 小时前
分布式一致性(三):共识的黎明——Quorum 机制与 Basic Paxos
分布式·后端·算法
only-qi2 小时前
leetcode24两两交换链表中的节点 快慢指针实现
数据结构·算法·链表
多恩Stone2 小时前
【3D AICG 系列-9】Trellis2 推理流程图超详细介绍
人工智能·python·算法·3d·aigc·流程图
sin_hielo2 小时前
leetcode 110
数据结构·算法·leetcode
整得咔咔响2 小时前
贝尔曼最优公式(BOE)
人工智能·算法·机器学习
日拱一卒——功不唐捐2 小时前
字符串匹配:暴力法和KMP算法(C语言)
c语言·算法
renke33642 小时前
Flutter for OpenHarmony:数字涟漪 - 基于扩散算法的逻辑解谜游戏设计与实现
算法·flutter·游戏