Largest Rectangle in Histogram

来源:互联网 发布:安捷伦数据采集仪 编辑:程序博客网 时间:2024/05/24 06:14

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.

For example,

Given height = [2,1,5,6,2,3], return 10.

栈内存储的是高度递增的下标。对于每一个直方图高度,分两种情况。1:当栈空

或者当前高度大于栈顶下标所指示的高度时,当前下标入栈。否则,2:当前栈顶

出栈,并且用这个下标所指示的高度计算面积。当i==length时设置为比数组中所有

元素都小的一个值-1,计算栈中剩余index对应的元素的面积。

public int largestRectangleArea(int[] height) {if(height==null||height.length<=0)return 0;Stack<Integer> stack = new Stack<Integer>();int max = 0;for (int i = 0; i <= height.length; i++) {int curt = (i == height.length) ? -1 : height[i];while (!stack.isEmpty() && curt <= height[stack.peek()]) {int h = height[stack.pop()];int w = stack.isEmpty() ? i : i - stack.peek() - 1;max = Math.max(max, h * w);}stack.push(i);}return max;}


0 0
原创粉丝点击