https://leetcode.cn/problems/largest-rectangle-in-histogram/description/?envType=study-plan-v2&envId=top-100-liked
84. 柱状图中最大的矩形
已解答
困难
相关标签
相关企业
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
这道题一看就不会,看了答案也没太理解,复杂题先放这吧。有机会再来。但是gpt说得应该是挺清楚的。
class Solution {
public int largestRectangleArea(int[] heights) {
// 初始化栈和变量
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
int index = 0;
// 遍历所有柱子
while (index < heights.length) {
// 如果当前柱子比栈顶柱子高,入栈
if (stack.isEmpty() || heights[index] >= heights[stack.peek()]) {
stack.push(index++);
} else {
// 计算矩形面积
int height = heights[stack.pop()];
// 计算宽度
int width = stack.isEmpty() ? index : index - stack.peek() - 1;
// 更新最大面积
maxArea = Math.max(maxArea, height * width);
}
}
// 处理栈中剩余的柱子
while (!stack.isEmpty()) {
int height = heights[stack.pop()];
int width = stack.isEmpty() ? index : index - stack.peek() - 1;
maxArea = Math.max(maxArea, height * width);
}
return maxArea;
}
}