84. Largest Rectangle in Histogram (JAVA)

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

 


Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

 

Idea: using dynamic programming.

Method I: first thought two arrays are stored leftward and rightward position of maximum extension position of maximum extension, on both sides of this method is to traverse, and space complexity O (n) + O (n)

Method II: a top element indicating the stack height to be calculated, the left boundary is the second element stack position +1 (since only the top of the stack is always the highest stack element height), the right boundary position of the current element -1 (the top element of the current element is lower than the case). When the current element height> = the height of the top element, the stack, i ++; if the current height of the element <element stack height, the stack, calculate a current area, I is not increased.

class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> st = new Stack<Integer>(); 
        if(heights.length == 0) return 0;
        
        int leftIndex;
        int topIndex;
        int area;
        int maxArea = 0; 
        int i = 0;
        while(i < heights.length){
            if(st.empty() || heights[i] >= heights[st.peek()]){
                st.push(i);
                I ++; 
            } 
            the else { 
                TopIndex = st.peek (); 
                st.pop (); 
                leftIndex = st.empty () 0:? st.peek () +. 1; // if it is empty, indicating that all were highly scratch than heights [topIndex] high 
                Area = ((. 1-I) + -leftIndex. 1) * heights [topIndex];
                 IF (Area> maxArea) maxArea = Area; 
            } 
        } 
        the while (st.empty ()!) { // no smaller than the top of the stack elements to make it popped 
            the TopIndex = st.peek (); 
            st.pop (); 
            leftIndex = st.empty () 0: st.peek () + 1? ;
            area = ((i-1)-leftIndex + 1) * heights[topIndex];
            if(area > maxArea) maxArea = area;
        }
        return maxArea;
    }
}

 

Guess you like

Origin www.cnblogs.com/qionglouyuyu/p/10938902.html