Tuesday, March 5, 2013

[LeetCode] Largest Rectangle in Histogram

Thought:
It is very interesting to use a stack to deal with this problem.
click here to view
Note: the pop value is an index, height[index] is its height.
          the width of the max area is how far it reaches from the current pop value to the left and right.
          i is the right bound, and s.peek() is the left bound( s.peek() is the first index whose height is smaller than current index's height).

Code:
public class Solution {
    public int largestRectangleArea(int[] height) {
        Stack<Integer> s = new Stack<Integer>();
        int i = 0;
        int result = 0;
        while (i < height.length) {
            if (s.isEmpty() || height[s.peek()] <= height[i]) {
                s.push(i);
                i++;           
            }else {
                result = Math.max(result, height[s.pop()] * (s.isEmpty() ? i : i - s.peek() - 1));
            }
        }
        while (!s.isEmpty()) {
            result = Math.max(result, height[s.pop()] * (s.isEmpty() ? i : i - s.peek() - 1));
        }  
        return result;
    }
}

No comments:

Post a Comment