leetcode 84 柱状图中最大的矩形
题目链接
做题过程
题目与接雨水类似。
但我们需要一个单调递增。
当减小时,就需要计算面积了。
同时我们需要重构heights数组使其首尾为0;
这样才能进入循环。
解决方法
class Solution {
public int largestRectangleArea(int[] heights) {
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;
Deque<Integer> stack = new LinkedList<>();
int res = 0;
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);
} else {
while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
int mid = stack.pop();
if (!stack.isEmpty()){
int w = i - stack.peek() - 1;
int h = heights[mid];
res = Math.max(res, h * w);
}
}
stack.push(i);
}
}
return res;
}
}