leetcode.84. 柱状图中最大的矩形

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

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

 

 

 

 

输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10

 

 

输入: heights = [2,4]
输出: 4

 

class Solution {
    public int largestRectangleArea(int[] heights) {
        int[] tmp = new int[heights.length + 2];
        System.arraycopy(heights, 0, tmp, 1, heights.length); 
        ////////////////////////////
        Deque<Integer> stack = new ArrayDeque<>();
        int area = 0;
        ////////////////////////////////
        for (int i = 0; i < tmp.length; i++) {
            /////////////////////
            while (!stack.isEmpty() && tmp[i] < tmp[stack.peek()]) {
                /////////////////////////////
                int h = tmp[stack.pop()];
                ///////////////////////
                area = Math.max(area, (i - stack.peek() - 1) * h);   
            }
            stack.push(i);//stack存数组索引
            ////////////////////////////
        }

        return area;
    }
}
posted @ 2022-08-02 23:42  开源遗迹  阅读(29)  评论(0)    收藏  举报