您的位置:首页 > 其它

84. Largest Rectangle in Histogram

2017-06-23 13:19 357 查看
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.

For example,

Given heights = 
[2,1,5,6,2,3]
,

return 
10
.
这道题考查单调栈的用法。这里的单调栈是单调递增栈,遇到比peek小的数,就开始弹栈,直到栈为空或者遇到比自己小的peek,并随时更新max。代码如下:
public class Solution {
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int max = 0;
for (int i = 0; i <= heights.length; i ++) {
int cur = i == heights.length? -1: heights[i];
while (!stack.isEmpty() && cur <= heights[stack.peek()]) {
int h = heights[stack.pop()];
int w = stack.isEmpty()? i: i - stack.peek() - 1;
max = Math.max(max, h * w);
}
stack.push(i);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: