给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
- 情况一:当前遍历的元素heights[i]大于栈顶元素heights[st.top()]的情况
- 情况二:当前遍历的元素heights[i]等于栈顶元素heights[st.top()]的情况
- 情况三:当前遍历的元素heights[i]小于栈顶元素heights[st.top()]的情况
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<>();
// 栈头到栈底单调递减
// 栈顶和栈顶的下一个元素以及要入栈的三个元素组成了我们要求最大面积的高度和宽度
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;
int result =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(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.push(i);
}
}
return result;
}
}