Tuesday, July 15, 2014

Largest rectangle area in histogram -- Leetcode

Answer:
复制代码
 1 public int largestRectangleArea2(int[] height) {
 2         Stack<Integer> stack = new Stack<Integer>();
 3         int i = 0;
 4         int maxArea = 0;
 5         int[] h = new int[height.length + 1];
 6         h = Arrays.copyOf(height, height.length + 1);
 7         while(i < h.length){
 8             if(stack.isEmpty() || h[stack.peek()] <= h[i]){
 9                 stack.push(i++);
10             }else {
11                 int t = stack.pop();
12                 maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i - stack.peek() - 1));
13             }
14         }
15         return maxArea;
16     }

No comments:

Post a Comment