描述
给出n个数字,代表直方图的条高,直方图每一条的宽度为1,请计算直方图中最大矩形的面积
上图是每条宽度为1, 高度 =[2,1,5,6,2,3].的直方图
图中的阴影部分是该直方图中面积最大的矩形,面积为10个单位
例如:
给出的高度 =[2,1,5,6,2,3],
返回10.
示例1
输入:
[2,1,5,6,2,3]
返回值:
10
/*
* Runtime: 24 ms.Your runtime beats 67.12 % of java submissions.
*/
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length < 1)
return 0;
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
int max = 0;
for (int i = 0; i < heights.length; i++) {
while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {
int top = stack.pop();
max = Math.max(max, (i - stack.peek() - 1) * heights[top]);
}
stack.push(i);
}
while (stack.peek() != -1) {
int top = stack.pop();
max = Math.max(max, (heights.length - 1 - stack.peek()) * heights[top]);
}
return max;
}