给定 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
/**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function(heights) {
let stack = [];
let l = new Array(heights.length),r = new Array(heights.length);
let n = heights.length;
for(let i = 0;i < n;i++) l[i] = -1,r[i] = n;
for(let i = 0;i < n;i++){
while(stack.length && heights[i] <= heights[stack[stack.length-1]]){
r[stack[stack.length - 1]] = i;
stack.pop();
}
if(stack.length) l[i] = stack[stack.length - 1];
stack.push(i);
}
let ans = 0;
for(let i = 0;i < n;i++){
ans = Math.max(ans,heights[i] * (r[i] - l[i] -1));
}
return ans;
};