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;
}
}
博客围绕LeetCode-084题“柱状图中最大的矩形”展开。思路是使用单调栈,当前高度大于栈顶高度入栈,小于则出栈并计算面积。为方便边界计算,给数组首尾加高度为0的柱。面积计算方式为栈顶高度乘以(当前元素索引 - 栈顶前一元素索引 - 1),还给出了代码。
214

被折叠的 条评论
为什么被折叠?



