84. 柱状图中最大的矩形 - 力扣(LeetCode)
单调栈:
java
class Solution {
public int largestRectangleArea(int[] heights) {
//单调栈
int n = heights.length;
int[] newHeights = new int[n+2];
//加哨兵0,第一个0是为了防止栈空,最后一个0是弹出所有的数
for(int i = 0;i<n;i++){
newHeights[i+1] = heights[i];
}
int maxArea = 0;
//存下标,因为要算width,需要用到下标
Deque<Integer> stack = new ArrayDeque<>();
for(int i = 0;i<n+2;i++){
while(!stack.isEmpty() && newHeights[i]<newHeights[stack.peek()]){
int mid = stack.pop();
int height = newHeights[mid];
int width = i-stack.peek()-1;
maxArea = Math.max(maxArea,height*width);
}
stack.push(i);
}
return maxArea;
}
}
时间复杂度:O(N)
空间复杂度:O(N)