84直方图最大矩形覆盖 · Largest Rectangle in Histogram

时间:2022-08-22 06:59:23

[抄题]:

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

84直方图最大矩形覆盖 · Largest Rectangle in Histogram

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

84直方图最大矩形覆盖 · Largest Rectangle in Histogram

The largest rectangle is shown in the shaded area, which has area = 10 unit.

[思维问题]:

[一句话思路]:

小高度使得全部大高度都终结了,对POP出来的面积打擂台

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. stack.peek() == 0 时属于非空
  2. max要初始化为0
  3. 可以用height[stack.peek()]来运用数组
  4. i = 0; i <= height.length 都要打印 比如1 1

[二刷]:

  1. 用三元运算符,curt到头了应该是-1,width在栈为空时就是i本身
  2. 在括号里pop了也算是完成了pop,不用再pop了

[总结]:

[复杂度]:Time complexity: O(n) push了n个但是只会pop出来一个 Space complexity: O(n)

[英文数据结构,为什么不用别的数据结构]:

[其他解法]:

[Follow Up]:

85 1拼出的最大矩形

[题目变变变]:

public class Solution {
public int largestRectangleArea(int[] height) {
if (height == null || height.length == 0) {
return 0;
} Stack<Integer> stack = new Stack<Integer>();
int max = 0;
for (int i = 0; i <= height.length; i++) {
int curt = (i == height.length) ? -1 : height[i];
while (!stack.isEmpty() && curt <= height[stack.peek()]) {
int h = height[stack.pop()];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(max, h * w);
}
stack.push(i);
} return max;
}
}