- 柱状图中最大的矩形
leetcode 困难题
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int largestRectangleArea(int[] heights) {
int max = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for(int i=0;i<heights.length;i++){
// 待入栈 heights[i]
while(stack.peek()!=-1&&(heights[stack.peek()]>=heights[i])){//代入栈的数小于栈顶元素
//求栈顶元素的最大面积
max = Math.max(max, heights[stack.pop()] * (i - stack.peek() -1) );
}
stack.push(i);
}
//栈不为空则
while(stack.peek()!=-1){
max = Math.max(max,heights[stack.pop()]*(heights.length-stack.peek()-1));
}
return max;
}
}