LC.P84[柱状图中最大的矩形]

方法一:单调栈

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
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length, ans = 0;
int[] l = new int[n], r = new int[n];
Arrays.fill(l, -1);
Arrays.fill(r, n);
Deque<Integer> stack = new ArrayDeque<>();
// 确定右边界
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) r[stack.pop()] = i;
stack.push(i);
}
stack.clear();
// 确定左边界
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) l[stack.pop()] = i;
stack.push(i);
}
for (int i = 0; i < n; i++) {
int height = heights[i], width = r[i] - l[i] - 1;
ans = Math.max(ans, height * width);
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$