largest-rectangle-in-histogram

/**
* 给出n个数字,代表直方图的条高,直方图每一条的宽度为1,请计算直方图中最大矩形的面积
*
* 上图是每条宽度为1, 高度 =[2,1,5,6,2,3].的直方图
*
* 图中的阴影部分是该直方图中面积最大的矩形,面积为10个单位
* 例如:
* 给出的高度 =[2,1,5,6,2,3],
* 返回10.
*/

/**
 * 给出n个数字,代表直方图的条高,直方图每一条的宽度为1,请计算直方图中最大矩形的面积
 *
 * 上图是每条宽度为1, 高度 =[2,1,5,6,2,3].的直方图
 *
 * 图中的阴影部分是该直方图中面积最大的矩形,面积为10个单位
 * 例如:
 * 给出的高度 =[2,1,5,6,2,3],
 * 返回10.
 */

public class Main59 {

    public static void main(String[] args) {
        int[] height = {0,9};
        System.out.println(Main59.largestRectangleArea(height));
    }

    public static int largestRectangleArea(int[] height) {

        if (height.length <= 0) {
            return 0;
        }
        int maxArea = 0;

        for (int i=0;i<height.length;i++) {
            int minLen = height[i];
//            maxArea = height[i]*1;
            for (int j=i;j<height.length;j++) {
                int area = 0;
                if (minLen > height[j]) {
                    area = height[j] * (j-i+1);
                    minLen = height[j];
                }else{
                    area = minLen* (j-i+1);
                }
                if (area > maxArea) {
                    maxArea = area;
                }
            }
        }
        return maxArea;
    }
}

  

原文地址:https://www.cnblogs.com/strive-19970713/p/11381368.html