leetcode:84. 柱状图中最大的矩形
题目描述
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例
输入: heights = [2,1,5,6,2,3]
输出: 10
解释: 最大的矩形为图中红色区域,面积为 10
解题思路
确定左右边界的矩形,其面积由组成它的最矮的柱子决定。
对于某个柱子,确定它是将要组成矩形中最矮的那个,单调栈找到它左右下一个更矮柱子,两个矮柱子中间就是它能延伸的最大宽度。即,固定高度找最大宽度,局部最大值。
完整代码:
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int[] r = new int[n];
Deque<Integer> stk = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stk.isEmpty() && heights[stk.getFirst()] > heights[i]) {
r[stk.removeFirst()] = i;
}
stk.addFirst(i);
}
while (!stk.isEmpty()) {
r[stk.removeFirst()] = n;
}
int res = 0;
for (int i = 0; i < n; i++) {
while (!stk.isEmpty() && heights[stk.getFirst()] >= heights[i]) {
stk.removeFirst();
}
int width = stk.isEmpty() ? r[i] : r[i] - stk.getFirst() - 1;
res = Math.max(res, width * heights[i]);
stk.addFirst(i);
}
return res;
}
}