84. Monotonic stack -- histogram

84. Largest rectangle in histogram

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

The top of the stack and the next element on the top of the stack and the three elements to be pushed into the stack constitute the height and width of the maximum area we require

Find the first column on the left and right sides of each column that is smaller than the column, so the order from the stack head (the element is popped from the stack head) to the bottom of the stack should be from large to small!

The following three situations:

  • Case 1: The heights[i] of the currently traversed element is smaller than the heights[st.peek()] of the top element of the stack

  • Case 2: The heights[i] of the currently traversed element is equal to the heights[st.peek()] of the top element of the stack

  • Case 3: The heights[i] of the currently traversed element is greater than the heights[st.peek()] of the top element of the stack

class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> st = new Stack<Integer>();
        int[] newheights = new int[heights.length + 2];
        newheights[0] = 0;
        newheights[newheights.length -1] =0;
        int sum =0;
        for(int i=0;i<heights.length;i++){
            newheights[i+1] = heights[i];
        }
        st.push(0);
        heights = newheights;

        for(int i=1;i<heights.length;i++){
            if(heights[i] > heights[st.peek()]){
                st.push(i);

            }else if(heights[i] == heights[st.peek()]){
                st.pop();
                st.push(i);
            }else{
                while(heights[i] < heights[st.peek()]){
                    int mid = st.peek();
                    st.pop();
                    int left = st.peek();
                    int right =i;
                    int w= right -left -1;
                    int h = heights[mid];
                    sum = Math.max(sum,w*h);
                }
                st.push(i);
            }
        }
return sum;
    }
}

Guess you like

Origin blog.csdn.net/weixin_56194193/article/details/129112255