84.柱状图中最大的矩形
完成
思路:
遍历数组,以其中的每个元素为基准,看其能扩散的最大矩形区域。利用单调栈,找到每个元素左右两边第一个比其小的元素位置,扩散到这个元素为止,算出当前基准元素所能达到的最大区域面积。
本题还有一个小技巧,在数组首尾加0,作为边界。之前的接雨水题目,没有在数组首尾添加元素作为边界,因为边界本身就接不到雨水。而本题边界的高度是要计算进去的。
代码
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<>();
stack.push(0);
int res = 0;
// 构造首尾为0的新数组
int[] newHeights = new int[heights.length+2];
newHeights[0] = 0;
for (int i = 1; i <= heights.length; i++) {
newHeights[i] = heights[i-1];
}
newHeights[newHeights.length-1]=0;
for (int i = 1; i < newHeights.length; i++) {
if(newHeights[stack.peek()]<newHeights[i]){
stack.push(i);
}else{
while(!stack.isEmpty()&&newHeights[stack.peek()]>newHeights[i]){
int mid = stack.pop();
if(!stack.isEmpty()){
int left = stack.peek();
int right = i;
res = Math.max(res, newHeights[mid]*(right-left-1));
}
}
stack.push(i);
}
}
return res;
}
}