代码随想录训练营二刷第六十二天 | 84.柱状图中最大的矩形

代码随想录训练营二刷第六十二天 | 84.柱状图中最大的矩形

一、84.柱状图中最大的矩形

题目链接:https://leetcode.cn/problems/largest-rectangle-in-histogram/
思路:和接雨水的思路类似,只不过反过来了,1,3,2。遇到右边第一个最小值,即可进行计算。

class Solution {
   public int largestRectangleArea(int[] heights) {
        int[] newHeights = new int[heights.length+2];
        for (int i = 0; i < heights.length; i++) {
            newHeights[i+1] = heights[i];
        }
        int max = 0;
        newHeights[0] = 0;
        newHeights[newHeights.length-1] = 0;
        heights = newHeights;
        Deque<Integer> stack = new LinkedList<>();
        stack.push(0);
        for (int i = 1; i < heights.length; i++) {
            if (heights[i] > heights[stack.peek()]) {
                stack.push(i);
            }else if (heights[i] == heights[stack.peek()]) {
                stack.pop();
                stack.push(i);
            }else {
                while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
                    int mid = stack.pop();
                    int w = i - stack.peek() -1;
                    int h = heights[mid];
                    max = Math.max(max, w*h);
                }
                stack.push(i);
            }
        }
        return max;
    }
}

你可能感兴趣的:(力扣算法题,数据结构,算法,动态规划,java,leetcode)