84. 柱状图中最大的矩形 - 力扣(LeetCode)
双指针思路,以当前数组为中心,借助两个数组存放当前数柱左右两侧小于当前数柱高度的索引,进行h*w的计算。注意首尾节点的左侧索引和右侧索引需要单独声名为0.
单调栈,在原数组的基础上定义一个新的数组,对其进行首尾节点的扩容。思路延续收集雨水。
class Solution {
public int largestRectangleArea(int[] heights) {
Stack stack = new Stack<>();
// 数组扩容
int[] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int i = 0; i < heights.length; i++) {
newHeights[i + 1] = heights[i];
}
heights = newHeights; // 改变数组引用
stack.add(0);
int result = 0;
for (int i = 1; i < heights.length; i++) {
if (heights[i] > heights[stack.peek()]) { // 入栈
stack.add(i);
} else if (heights[i] == heights[stack.peek()]) {
stack.pop(); // 弹出
stack.add(i); // 入栈
} else {
while (heights[i] < heights[stack.peek()]) {
int mid = stack.peek(); // 当前数值柱子
stack.pop();
int left = stack.peek();
int right = i;
int w = right - left - 1;
int h = heights[mid];
result = Math.max(result, w * h);
}
stack.add(i);
}
}
return result;
}
}
时间复杂度:O(n).
空间复杂度:O(n).符合单调递减的情况时,全部入栈。