LeetCode-084-柱状图中最大的矩形
思路
详细参考 动画演示 单调栈 84.柱状图中最大的矩形 - 柱状图中最大的矩形 - 力扣(LeetCode) (leetcode-cn.com)
- 使用单调栈解决:当前高度大于于栈顶高度,入栈;当前高度小于栈顶高度,出栈,计算面积
- 给数组首尾分别加上高度为0的柱,方便边界计算,且不用判断栈空
- 面积=栈顶高度*(当前元素的索引-栈顶前一个元素的索引-1)
代码
class Solution {
public int largestRectangleArea(int[] heights) {
//增加首尾用于放置高度为0的柱,保证边界条件,且不用判断栈空
int []arr=new int[heights.length+2];
for(int i=0;i<heights.length;i++){
arr[i+1]=heights[i];
}
int res=0;
Stack<Integer> st=new Stack<>();
for(int i=0;i<arr.length;i++){
while(!st.isEmpty()&&arr[i]<arr[st.peek()]){
int h=arr[st.pop()];
int w=i-st.peek()-1;
res=Math.max(res,h*w);
}
st.push(i);
}
return res;
}
}