给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3] 输出:10 解释:最大的矩形为图中红色区域,面积为 10
整体思路:还是单调栈的思路,不多赘述了。
class Solution {
public int largestRectangleArea(int[] heights) {
int len=heights.length;
int[] arr=new int[len+2];
arr[0]=0;
int index=1;
int res=0;
for(int i=0;i<len;i++){
arr[index]=heights[i];
index++;
}
arr[index]=0;
Stack<Integer> stack=new Stack<>();
stack.push(0);
for(int i=1;i<len+2;i++){
while(!stack.isEmpty()&&arr[i]<arr[stack.peek()]){
int h=arr[stack.pop()];
int w=i-stack.peek()-1;
res=Math.max(res,h*w);
}
stack.push(i);
}
return res;
}
}
一刷结束,一周之后开启二刷,持续进步,加油冲冲冲!!