算法代码

柱状图中面积最大的矩形

2020-06-06  本文已影响0人  windUtterance

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

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

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

图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
输入: [2,1,5,6,2,3]
输出: 10

Java代码

class Solution {
    public int largestRectangleArea(int[] heights) {
        int len = heights.length;
        if(len == 0) return 0;
        if(len == 1) return heights[0];
        int res = 0;

        int[] new_heights = new int[len + 2];
        new_heights[0] = 0;
        System.arraycopy(heights, 0, new_heights, 1, len);
        new_heights[len + 1] = 0;
        len += 2;
        heights = new_heights;

        Deque<Integer> stack = new ArrayDeque<>(len);
        stack.addLast(0);

        for(int i = 0;i < len;i++) {
            while(heights[i] < heights[stack.peekLast()]) {
                int cur_height = heights[stack.pollLast()];
                int cur_width = i - stack.peekLast() - 1;
                res = Math.max(res, cur_height * cur_width);
            }
            stack.addLast(i);
        }

        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读