2014年5月10日星期六

Loop Solution - Largest Rectangle in Histogram - DP idea *

The idea below is combined with loop and DP thinking. The processing height array is defined one more than original array, and assign 0 to force the code back tracking everything ahead!

public class Solution {
    public int largestRectangleArea(int[] height) {
        if(height == null || height.length == 0){
            return 0;
        }
       
        int[] processHeight = new int[height.length + 1];
        for(int i = 0; i < height.length; i++){
            processHeight[i] = height[i];
        }
        processHeight[height.length] = 0;
       
        Stack<Integer> process = new Stack<Integer>();
        int index = 0;
        int sum = 0;
        while(index < processHeight.length){
            if(process.isEmpty() || processHeight[index] > processHeight[process.peek()]){
                process.push(index);
            }else{
                int cur = process.pop();
                sum = Math.max(sum, ((process.isEmpty()) ? index : index - process.peek() - 1) * processHeight[cur]);
                index--;
            }
            index++;
        }
        return sum;
    }
}

没有评论: