柱状图中最大的矩形
柱状图中最大的矩形
递减栈
注意:
1.heights首尾添加0。考虑边界情况:heights为递增数组或递减数组
var largestRectangleArea = function(heights) {
let stack = [];
stack.push(0);
let res=0
heights.unshift(0)
heights[heights.length]=0
for (let i = 1; i < heights.length; i++) {
const top = stack[stack.length - 1];
if (heights[top] <= heights[i]) {
stack.push(i);
} else {
while (
stack.length >= 1 &&
heights[stack[stack.length - 1]] > heights[i]
) {
let mid = stack.pop();
if(stack.length >= 1){
let h= heights[mid]
let width=i -stack[stack.length-1]-1
res=Math.max(res,h*width)
}
}
stack.push(i);
}
}
return res;
};