public int largestRectangleArea(int[] height){
int area = 0;
Stack<Integer> heightStack = new Stack<Integer>();
Stack<Integer> indexStack = new Stack<Integer>();//存放的是大于等于当前值的最左块
for(int i = 0; i <height.length; i++){
if(heightStack.empty() || heightStack.peek() <= height[i]){
heightStack.push(height[i]);
indexStack.push(i);
}else if(heightStack.peek() > height[i]){
int j = 0;
while(!heightStack.empty() && heightStack.peek() > height[i]){
j = indexStack.pop();
int currArea = (i - j) * heightStack.pop();//面积不算当前块
if(currArea > area){
area = currArea;
}
}
heightStack.push(height[i]);
indexStack.push(j);
}
}
while(!heightStack.isEmpty()){
int currArea = (height.length - indexStack.pop()) * heightStack.pop();
if(currArea > area){
area = currArea;
}
}
return area;
}
若heightStack为空或者当前高度大于heightStack栈顶,则当前高度和当前下标分别入站(下面有一个解法可以只用一个栈即可,用栈来保存下标,而高度由下标很容易得到)。所以heightStack记录了一个连续递增的序列。
若当前高度小于heightStack栈顶,heightStack和indexStack出栈,直到当前高度大于等于heightStack栈顶。出栈时,同时计算区间所形成的最大面积。注意计算完之后,当前值入栈的时候,其对应的下标应该为最后一个从indexStack出栈的下标。
please refer to http://www.cnblogs.com/avril/archive/2013/08/24/3278873.html