单调栈很重要的性质,就是单调栈里的顺序,是从小到大还是从大到小。
栈顶和栈顶的下一个元素以及要入栈的三个元素组成了我们要求最大面积的高度和宽度!!
依旧是分析清楚如下三种情况:
- class Solution {
- public int largestRectangleArea(int[] heights) {
- int[] newHeight = new int[heights.length + 2];
- System.arraycopy(heights, 0, newHeight, 1, heights.length);
- newHeight[heights.length+1] = 0;
- newHeight[0] = 0;
-
- Stack<Integer> stack = new Stack<>();
- stack.push(0);
-
- int res = 0;
- for (int i = 1; i < newHeight.length; i++) {
- while (newHeight[i] < newHeight[stack.peek()]) {
- int mid = stack.pop();
- int w = i - stack.peek() - 1;
- int h = newHeight[mid];
- res = Math.max(res, w * h);
- }
- stack.push(i);
-
- }
- return res;
- }
- }