- 84.柱状图中最大的矩形
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<>();
stack.push(0);
int ans = 0;
int [] nh = new int[heights.length + 2];
nh[0] = 0;
nh[nh.length - 1] = 0;
for (int index = 0; index < heights.length; index++) {
nh[index + 1] = heights[index];
}
heights = nh;
for (int i = 1; i < heights.length; i++) {
if (heights[i] >= heights[stack.peek()]) {
stack.push(i);
} else {
while (heights[i] < heights[stack.peek()]) { // 注意是while
int mid = stack.peek();
stack.pop();
int left = stack.peek();
int right = i;
int w = right - left - 1;
int h = heights[mid];
ans = Math.max(ans, w * h);
}
stack.push(i);
}
}
return ans;
}
}