题目:Largest Rectangle in Histogram
难度:hard
问题描述:
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 heights = [2,1,5,6,2,3]
,
return 10
.
解题思路:求最大矩形。很难的一道题,我是看了提示使用了stack才解出来。stack中存储的是方块的下标索引号,如果当前方块的高度大于等于栈顶元素对应方块的高度,那么就将该方块的索引号进栈。那么每个栈元素的下面一层就是它的左边界。当遇到当前方块的高度小于栈顶元素对应方块的高度,则出栈,出栈元素的右边界则为当前方块。然后再将当前元素入栈。这样每个元素都会入栈,下一层就是左边界,每个元素都会出栈,使它出栈的元素则是它的右边界。
当所有元素便利后,剩余栈内元素的右边界就是len-1.
具体代码如下:
public static int largestRectangleArea(int[] heights) {
int len=heights.length;
int res=0;
int temp;
int left=0,right=0;
int i;
Stack<Integer> stack=new Stack<>();
for(i=0;i<len;i++){
if(stack.isEmpty()){
stack.push(i);
continue;
}
while(!stack.isEmpty()){
if(heights[stack.peek()]<=heights[i]){
break;
}else{
temp=stack.pop();
right=i-1;
if(stack.isEmpty()){
left=0;
}else{
left=stack.peek()+1;
}
res=res>(right-left+1)*heights[temp]?res:(right-left+1)*heights[temp];
}
}
stack.push(i);
}
while(!stack.isEmpty()){
int top=heights[stack.pop()];
int size=top*(stack.isEmpty()?i:i-stack.peek()-1);
res=Math.max(res, size);
}
return res;
}