leetcode-84 Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

 


Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

 


The largest rectangle is shown in the shaded area, which has area = 10 unit.

 

Example:

Input: [2,1,5,6,2,3]
Output: 10

 

找出最大的矩形,并返回其面积:

方法一:暴力搜索对其所有结果进行遍历。最终超时。

    public int largestRectangleArea(int[] heights) {
        int n = heights.length;
        int[][]res = new int[n][n];
        for(int i=0;i<n;i++) {
            int min = heights[i];
            for(int j=i;j<n;j++) {
                min = Math.min(min, heights[j]);
                res[i][j] = min*(j-i+1);
                if(i==0 && j==0) {
                    continue;
                }else {
                    if (i > 0) {
                        res[i][j] = Math.max(res[i][j], res[i - 1][j]);
                    }
                    if(j>0) {
                        res[i][j] =Math.max(res[i][j], res[i][j-1]);
                    }
                }

                
            }
        }
        return n==0 ?0:res[n-1][n-1];
    }

 

方法二:优化方法:找出每一个局部波峰值,当前的数字大于后面的数字,只计算出这些波峰值之间的最大值面积,进行比较

    public int largestRectangleArea(int[] heights) {
        int max = 0;
        for (int i = 0; i < heights.length; i++) {
            // 调过非波峰值的结果
            if (i + 1 < heights.length && heights[i] <= heights[i + 1]) {
                continue;
            }
            int height = heights[i];
            for (int j = i; j >= 0; j--) {
                height = Math.min(height, heights[j]);
                max = Math.max(max, height * (i - j + 1));
            }

        }
        return max;
        
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值