84. 柱状图中最大的矩形

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

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

 

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

 

图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

 

示例:

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

方法1:分治
class Solution {
    public int largestRectangleArea(int[] heights) {
        //分治 —— 关键,找出最低点
        return getL(heights,0,heights.length - 1);
    }
    
    private int getL(int[] nums,int start,int end){
        if(start > end){
            return 0;
        }
        int index = start;
        for(int i = start;i <= end;i++){
            if(nums[i] < nums[index]) index = i;
        }
        return Math.max(nums[index] * (end - start + 1),Math.max(getL(nums,start,index - 1),getL(nums,index + 1,end)));
    }
}

 方法2:单调栈

class Solution {
    public int largestRectangleArea(int[] hei) {
        if(hei == null || hei.length == 0) return 0;
        //单调递增栈
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        int res = Integer.MIN_VALUE;
        for(int i = 0;i < hei.length;i++){
            while(stack.peek() != -1 && hei[stack.peek()] >= hei[i]){
                //处理i - 1前的
                res = Math.max(res,hei[stack.pop()] * (i - stack.peek() - 1));
            }
            stack.push(i);
        }
        while(stack.peek() != -1){
            res = Math.max(res,hei[stack.pop()] * (hei.length - stack.peek() - 1));
        }
        return res;
    }

}

 

posted @ 2020-04-11 18:52  海绵爱上星  阅读(147)  评论(0)    收藏  举报