Wednesday, March 20, 2013

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.

using a stack, when the next height is larger, push its position into the stack, otherwise, pop a position and calculate the area of the maximum rectangle that can be formed using the height at the position.

remember: the bar right next to the top position at the stack after pop is always larger or equal to the bar at the poped position.

public class Solution {
    public int largestRectangleArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(height==null || height.length == 0) return 0;
        LinkedList<Integer> stack = new LinkedList<Integer>();
        int i = 1;
        int ret = height[0];
        while( i < height.length + 1){
            int nextv = i < height.length? height[i] : 0;
            if(stack.isEmpty() || height[stack.getLast()] <= nextv)
                int t = stack.removeLast();
                ret = Math.max(ret, height[t] * (stack.isEmpty() ? i : i-1-stack.getLast()) );
        return ret;

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm