视频讲解:【LeetCode84_柱状图中最大的矩形_单调栈】 https://www.bilibili.com/video/BV1gg411Q71Z?share_source=copy_web&vd_source=a1d10c96be67b4b38a41d23ddbab3cc1
class Solution {
public int largestRectangleArea(int[] heights) {
int result = 0;
int[] newHeights = new int[heights.length + 2];
int length = newHeights.length;
// 左边的0主要是为了得到高度应有的宽度
newHeights[0] = 0;
// 右边的0主要是为了破坏单调递增栈的单调性
newHeights[length - 1] = 0;
System.arraycopy(heights, 0, newHeights, 1, heights.length);
Deque<Integer> stack = new LinkedList<>();
// 放入左边的0的索引
stack.push(0);
for (int i = 1; i < length; i++) {
while (!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {
// 破坏单调递增栈,对最大矩形面积做更新
int currentHeight = newHeights[stack.pop()];
// stack.peek()表示上一个比当前高度小的值的索引
int width = i - stack.peek() - 1;
result = Math.max(result, currentHeight * width);
}
// 两种含义
// 1,维护当前单调递增栈
// 2,建立新的单调递增栈
stack.push(i);
}
return result;
}
}