算法训练营第六十天|84.柱状图中最大的矩形

82 阅读1分钟

84. 柱状图中最大的矩形

其实就是反向接雨水,接雨水是找每个柱子左右两边第一个大于该柱子高度的柱子,而本题是找每个柱子左右两边第一个小于该柱子的柱子。

class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> monoStack = new Stack<>();
        int res = 0;

        int[] newHeights = new int[heights.length + 2];
        newHeights[0] = 0;
        newHeights[newHeights.length - 1] = 0;
        for(int i = 0; i < heights.length; i++){
            newHeights[i + 1] = heights[i];
        }

        heights = newHeights;

        for(int i = 0; i < heights.length; i++){
            while(!monoStack.isEmpty() && heights[monoStack.peek()] > heights[i]){
                int mid = monoStack.pop();
                int w = i - monoStack.peek() - 1;
                int h = heights[mid];
                res = Math.max(res, w * h);
            }
            monoStack.push(i);
        }
        return res;
    }
}