largest-rectangle-in-histogram Java code

来源:互联网 发布:caffe cn 编辑:程序博客网 时间:2024/05/20 06:26

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 =10unit.
For example,
Given height =[2,1,5,6,2,3],
return10.

public class Solution {    public int largestRectangleArea(int[] height) {        int max = 0;        for(int i = 0; i < height.length; i++){            int len = 1;            for(int j = i - 1; j >= 0; j--){                if(height[j] >= height[i]){                    len++;                }else {                    break;                }            }            for(int k = i + 1; k < height.length; k++){                if(height[k] >= height[i]){                    len++;                }else {                    break;                }            }            max = Math.max(max,len * height[i]);        }        return max;    }}
原创粉丝点击