2014年2月19日星期三

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



The largest rectangle is shown in the shaded area, which has area = 10 unit.


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

public class Solution {
    public int largestRectangleArea(int[] height) {
        Stack<Integer> stack = new Stack<Integer>();
        int i = 0;
        int maxArea = 0;
        for(i=0;i<=height.length;i++) {
            int hh = 0;
            if(i!=height.length) {
                hh = height[i];
            }
            if((stack.isEmpty() || height[stack.peek()] <= hh)){
                stack.push(i);
            }else {
                // each t will be popped up exactly once
                // i is the rightmost index where h[i-1]>=h[t]
                int t = stack.pop();
               // stack.peek() is the leftmost index where h[stack.peek()+1] >=h[t]
               // so the rectangle with height h[t], is from stack.peek() + 1 to i-1
                maxArea = Math.max(maxArea, height[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
                i--;
            }
        }
        return maxArea;
    }
}

没有评论:

发表评论