leetcode 84. Largest Rectangle in Histogram

leetcode 84. Largest Rectangle in Histogram

题目

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].

leetcode 84. Largest Rectangle in Histogram_第1张图片
The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given heights = [2,1,5,6,2,3],
return 10.

public class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> stack=new Stack<Integer>();
        int ret=0;
        for(int i=0;i<heights.length;i++){

            if(stack.empty()|| (stack.peek()<=heights[i]) ){

                stack.push(heights[i]);
            }else{
                int count=0;
                while(!stack.empty()&&stack.peek()>heights[i]){

                    count++;
                    ret=Math.max(ret,stack.peek()*count);
                    stack.pop();

                }
                while(count-->0){
                    stack.push(heights[i]);

                }
                stack.push(heights[i]);
            }
        }

        int count=1;
        while(!stack.empty()){
            ret=Math.max(ret,stack.peek()*count);
            stack.pop();
            count++;
        }

        return ret;


    }
}

小结

1,Stack类在java.util.*中;
2,Stack的常用方法pop( ),push( ) ,peel( ), empty( );
3,Math.max( a,b)用于得到a,b中的较大值。

你可能感兴趣的:(LeetCode)