For循环以每个柱子为基准,找左右比它小的柱子,特点需要首尾加0,不然可能会空栈操作。找到比它小的就代表不能延申.用递减单调栈。
class Solution {
public int largestRectangleArea(int[] heights) {
Deque<Integer> stack=new LinkedList<>();
int[] newHeights=new int[heights.length+2];
for(int i=1;i<heights.length+1;i++){
newHeights[i]=heights[i-1];//要给左右两边赋0,防止空栈操作或找不到比它小的
}
int maxArea=0;
for(int i=0;i<newHeights.length;i++){
while(!stack.isEmpty()&&newHeights[i]<newHeights[stack.peek()]){
//碰到小的无法延申,弹出
int mid=stack.pop();
int left=stack.peek();
int area=newHeights[mid]*(i-left-1);
if(area>maxArea) maxArea=area;
}
stack.push(i);
}
return maxArea;
}
}