*LeetCode-Largest Rectangle in Histogram

http://www.geeksforgeeks.org/largest-rectangle-under-histogram/

public class Solution {
    public int largestRectangleArea(int[] height) {
        if ( height == null || height.length == 0 )
            return 0;
        int n = height.length;
        Stack<Integer> stack = new Stack<Integer>();
        stack.push( 0 );
        int max = height[0];
        for ( int i = 1; i < n; i ++ ){
            if ( stack.isEmpty() || height [i] >= height[ stack.peek () ] ){
                stack.push ( i );
            }
            else {
                int cur = stack.pop();
                max = Math.max ( max, height[ cur ] * ( stack.isEmpty() ? i : i - stack.peek() - 1));
                i --;  //这里要很注意 这次没有push的话不能跳过去
            }
        }
        while ( !stack.isEmpty() ){
            int cur = stack.pop();
            max = Math.max ( max, height[ cur ] * ( stack.isEmpty() ? n : n - stack.peek() - 1));            
        }
        return max;
    }
}


你可能感兴趣的:(*LeetCode-Largest Rectangle in Histogram)