0
点赞
收藏
分享

微信扫一扫

84. 柱状图中最大的矩形


84. 柱状图中最大的矩形

双指针

class Solution {
    public int largestRectangleArea(int[] heights) {
        int n = heights.length;
        int[] minLeftIndex = new int[n];
        int[] minRightIndex = new int[n];

        minLeftIndex[0] = -1;
        for(int i = 1; i < n; i++){
            int t = i - 1;
            while(t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t];
            minLeftIndex[i] = t;
        }

        minRightIndex[n - 1] = n;
        for(int i = n - 2; i >= 0; i--){
            int t = i + 1;
            while(t < n && heights[t] >= heights[i]) t = minRightIndex[t];
            minRightIndex[i] = t;
        }

        int res = 0, sum = 0;
        for(int i = 0; i < n; i++){
            sum = heights[i] * (minRightIndex[i] - minLeftIndex[i] - 1);
            res = Math.max(res, sum);
        }

        return res;
    }
}

单调栈

class Solution {
    public int largestRectangleArea(int[] heights) {
        int len = heights.length + 2;
        int[] newHeight = new int[len];
        for(int i = 1; i < len - 1; i++) newHeight[i] = heights[i - 1];

        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(0);

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

        return res;
    }
}


举报

相关推荐

0 条评论