84.柱状图中最大的矩形
力扣题目链接
class Solution {
public int largestRectangleArea(int[] heights) {
Deque<Integer> stack = new LinkedList<>();//单调递增的栈,保存的是高度数组的下标
int result = 0;
// 数组扩容,在头和尾各加入一个元素
int [] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int index = 0; index < heights.length; index++){
newHeights[index + 1] = heights[index];
}
heights = newHeights;
stack.push(0);
for(int i = 1;i < heights.length;i++){
if(heights[i] > heights[stack.peek()]){
stack.push(i);
}else if(heights[i] == heights[stack.peek()]){
stack.pop();
stack.push(i);//w = i - left - 1。开头我们又添加了0,所以弹出了也不影响最后算w,不弹出反而会多算一次。
}else{
while(!stack.isEmpty() && heights[i] < heights[stack.peek()]){
int mid = stack.pop();
int left = stack.peek();
int width = i - left - 1;
int height = heights[mid];
result = Math.max(result,width * height);
}
stack.push(i);
}
}
return result;
}
}