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.
算法:
1. if height[i]>=stack.peek(), push
2. if height[i]< stack.peek(), pop
这题naive的方法就是遍历所有的height,每一个height往两边找最远的点:O(n^2)
对于x, 栈里面保存了左边最远的点(左邻居),而右边最远的点就是当x pop out时,进栈点i的左邻居, 也就是 i-1.
栈里面保存index,才能方便的算出矩形的底边
[code]
public class Solution {
public int largestRectangleArea(int[] height) {
Stack<Integer> stack=new Stack<Integer>();
if(height==null || height.length==0)return 0;
stack.push(0);
int i=1, max=0;
for(i=1;i<height.length;i++)
{
int top=stack.peek();
if(height[top]<=height[i])
{
stack.push(i);
}
else
{
int end=top;
while(stack.size()>0 && height[stack.peek()]>=height[i])
{
top=stack.pop();
max= stack.size()==0 ? Math.max(max, i*height[top]) : Math.max(max, (i-stack.peek()-1)*height[top]);
}
stack.push(i);
}
}
if(stack.size()>0)
{
int end=stack.peek(), start=end;
while(stack.size()>0)
{
start=stack.pop();
max= stack.size()==0 ? Math.max(max, (end+1)*height[start]) : Math.max(max, (end-stack.peek())*height[start]);
}
}
return max;
}
}