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

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

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

题目链接
思路:单调栈内自栈顶到栈底单调递减,当前元素小于栈顶,栈顶即为凸点。

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];
        }
        newHeights[0] = 0;
        newHeights[newHeights.length-1] = 0;
        heights = newHeights;
        int sum = 0;
        Deque<Integer> stack = new LinkedList<>();
        stack.push(0);
        for (int i = 1; i < heights.length; i++) {
            while (heights[i] < heights[stack.peek()]) {
                int mid = stack.pop();
                int h = heights[mid];
                int w = i - stack.peek() - 1;
                sum = Math.max(sum, h*w);
            }
            stack.push(i);
        }
        return sum;
    }
}

你可能感兴趣的:(算法)