题目链接:https://leetcode.cn/problems/largest-rectangle-in-histogram/
题目介绍:
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10
思路:
代码:
class Solution {
public int largestRectangleArea(int[] heights) {
int[] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int i = 0; i < heights.length; i++) {
newHeights[i + 1] = heights[i];
}
heights = newHeights;
int result = 0;
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
for (int i = 1; i < heights.length; i++) {
if (heights[i] >= heights[stack.peek()]) {
stack.push(i);
} else {
while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
int mid = stack.pop();
if (!stack.isEmpty()) {
int left = stack.peek();
int right = i;
int h = heights[mid];
int w = right - left - 1;
result = Math.max(result, h * w);
}
}
stack.push(i);
}
}
return result;
}
}