84. 柱状图中最大的矩形

Smile_slime_47

原题地址:https://leetcode.cn/problems/largest-rectangle-in-histogram/

题解

单调栈,分别用两个数组,leftMin[i]记录i左侧第一个高度小于i的下标,rightMin[i]记录i右侧第一个高度小于i的下标

对于以height[i]为高度的矩形,我们可以知道其面积为

取所有矩形面积的最大值即可

时间复杂度:O(N)

空间复杂度:O(N)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack=new Stack<>();
int[] leftMin=new int[heights.length];
int[] rightMin=new int[heights.length];
int max=Integer.MIN_VALUE;


for (int i=0;i<heights.length;i++){
while (!stack.isEmpty()){
if(heights[stack.peek()]>=heights[i]){
stack.pop();
}else{
leftMin[i]=stack.peek();
stack.push(i);
break;
}
}
if(stack.isEmpty()){
leftMin[i]=-1;
stack.push(i);
}
}
stack=new Stack<>();
for (int i= heights.length-1;i>=0;i--){
while (!stack.isEmpty()){
if(heights[stack.peek()]>=heights[i]){
stack.pop();
}else{
rightMin[i]=stack.peek();
stack.push(i);
break;
}
}
if(stack.isEmpty()){
rightMin[i]=heights.length;
stack.push(i);
}
max=Math.max(max,heights[i]*(rightMin[i]-leftMin[i]-1));
}
return max;
}
}
Comments
On this page
84. 柱状图中最大的矩形