【代码随想录Day60】单调栈

84.柱状图中最大的矩形

https://leetcode.cn/problems/largest-rectangle-in-histogram/

class Solution {         // mono increasing stack [1(index 1)   2(index 4)]        area = (cur index - pre index + 1) * pre height
    public int largestRectangleArea(int[] heights) {
        int globalMax = 0;
        Deque stack = new ArrayDeque<>();
        for (int i = 0; i <= heights.length; i++) {
            int cur = i == heights.length ? 0 : heights[i];
            while (!stack.isEmpty() && heights[stack.peek()] >= cur) {
                int heightIndex = stack.pollFirst();
                int preIndex = stack.isEmpty() ? 0 : stack.peekFirst() + 1;
                globalMax = Math.max(heights[heightIndex] * (i - preIndex), globalMax);   //bug 右边界是i - 1
            }                
            stack.offerFirst(i);
        }
        return globalMax;
    }
}

你可能感兴趣的:(代码随想录,leetcode,算法)