Description:
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.
Explanation:
给出 height = [2,1,5,6,2,3],返回 10
Solution:
计算以当前值为高的矩形面积,所以要找到它的左右边界。建立栈,存储当前元素在数组中的位置。将数组元素一次推入栈中,如果它比栈顶元素小,则栈顶元素的右边界出现了,现在确定他的左边界。此时将栈顶元素出栈。栈中都是比当前元素小的值,因为比当前值大的都因当前值而出栈,所以,可以借此确定当前矩形的左边界,如果栈为空,说明当前元素是栈中最小值,左边界就是0。知道左右边界之后就可以计算面积了,高度是当前值,宽度是 i 或者 i-stack.peek()-1,为什么再-1?因为是左边界,已经不在矩形范围内了,当前值已经出栈了。
public class Solution {
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
public int largestRectangleArea(int[] height) {
// write your code here
if(height.length == 0) return 0;
int[] high = Arrays.copyOf(height , height.length + 1);
int result = 0;
Stack<Integer> rank = new Stack<Integer>();
for(int i = 0;i<high.length;i++){
while(!rank.isEmpty() && high[i] < high[rank.peek()] ){
int area = high[rank.pop()]*(rank.isEmpty()?i:i-rank.peek() - 1);
result = Math.max(result , area);
}
rank.push(i);
}
return result;
}
}