Loading

LeetCode 84 柱状图中最大的矩形

LeetCode84 柱状图中最大的矩形

题目描述

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

image-20201120125043443.png

以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]

image-20201120125054200.png

样例

输入: [2,1,5,6,2,3]
输出: 10

算法分析

  • 枚举上边界,找到左边第一个比他小的柱子,和右边第一个比他小的柱子
  • 面积 (r - l - 1)* h[i]
  • 单调栈使用

时间复杂度

Java代码

class Solution {
    public int largestRectangleArea(int[] h) {
        if(h.length == 0) return 0;
        int n = h.length;
        Stack<Integer> stk = new Stack<Integer>();
        int[] left = new int[n];
        int[] right = new int[n];

        for(int i = 0; i < n; i ++){
            while(!stk.isEmpty() && h[stk.peek()] >= h[i]) stk.pop();
            if(stk.isEmpty()) left[i] = -1;
            else left[i] = stk.peek();
            stk.push(i);
        }


        stk.clear();
        for(int i = n - 1; i >= 0; i --){
            while(!stk.isEmpty() && h[stk.peek()] >= h[i]) stk.pop();
            if(stk.isEmpty()) right[i] = n;
            else right[i] = stk.peek();
            stk.push(i);
        }

        int res = 0;
        for(int i = 0; i < n; i ++){
            res = Math.max(res,h[i]*(right[i] - left[i] - 1));
        }

        return res;
    }
}
posted @ 2020-11-20 13:36  想用包子换论文  阅读(88)  评论(0)    收藏  举报