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.
利用单调递增栈记录比当前高度低的栈
当发现某一个条形的左边比它矮的条形和右边比他矮的条形时可以进行一次清算
public int largestRectangleArea(int[] heights) {
int maxArea = 0;
Stack<Integer> s = new Stack<Integer>();
for(int i = 0; i <= heights.length; i++){
int h = (i == heights.length ? 0 : heights[i]);
if(s.isEmpty() || h >= heights[s.peek()]){
s.push(i);
}else{
int tp = s.pop();
maxArea = Math.max(maxArea, heights[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}