LeetCode 84 柱状图中最大的矩形
LeetCode84 柱状图中最大的矩形
题目描述
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。

以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。

样例
输入: [2,1,5,6,2,3]
输出: 10
算法分析
- 枚举上边界,找到左边第一个比他小的柱子,和右边第一个比他小的柱子
- 面积 (r - l - 1)* h[i]
- 单调栈使用
时间复杂度
Java代码
class Solution {
public int largestRectangleArea(int[] h) {
if(h.length == 0) return 0;
int n = h.length;
Stack<Integer> stk = new Stack<Integer>();
int[] left = new int[n];
int[] right = new int[n];
for(int i = 0; i < n; i ++){
while(!stk.isEmpty() && h[stk.peek()] >= h[i]) stk.pop();
if(stk.isEmpty()) left[i] = -1;
else left[i] = stk.peek();
stk.push(i);
}
stk.clear();
for(int i = n - 1; i >= 0; i --){
while(!stk.isEmpty() && h[stk.peek()] >= h[i]) stk.pop();
if(stk.isEmpty()) right[i] = n;
else right[i] = stk.peek();
stk.push(i);
}
int res = 0;
for(int i = 0; i < n; i ++){
res = Math.max(res,h[i]*(right[i] - left[i] - 1));
}
return res;
}
}

浙公网安备 33010602011771号