给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10
示例 2:
输入: heights = [2,4]
输出: 4
提示:
1 <= heights.length <=105
0 <= heights[i] <= 104
class Solution {
int[] stk; //定义栈
int tt; //定义栈顶
public int largestRectangleArea(int[] heights) {
int n = heights.length;
if(n == 1) return heights[0];
int res = 0;
int[] newHeights = new int[n+2];
//添加哨兵
newHeights[0] = 0;
System.arraycopy(heights,0,newHeights,1,n);
newHeights[n+1] = 0;
heights = newHeights;
n += 2;
//定义栈
stk = new int[n+2];
for(int i = 1; i < n; ++i){
while(tt > 0 && heights[stk[tt]] > heights[i]){
//出栈
int curHeight = heights[stk[tt--]];
int left = stk[tt] + 1;
int right = i - 1;
res = Math.max(res,(right-left+1)*curHeight);
}
stk[++tt] = i;
}
return res;
}
}