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

 

思路:计算以height[i]为最低点时的最大面积。

1. 创建一个栈stack;

1. 从头开始遍历数组,如果数组为空或者当前遍历元素height[i]>=stack.peek(),就将"i"进栈,注意是将"i"而不是height[i];

3. 如果height[i]<stack.peek();

  计算以height[stack.pop()]为最短高度,长度为i-stack.peek()-1的面积;

  如果此时stack为空,则长度为"i";

  如果计算得到的面积大,则更新当前最大面积max;

4. 当遍历到数组结束时,添加一个元素“0”作为终点判断。

 

代码如下:

 1 public int largestRectangleArea(int[] height) {
 2         if(height == null || height.length == 0) return 0;
 3         Stack<Integer> stack = new Stack<Integer>();
 4         stack.push(-1);
 5         int maxArea = 0;
 6         for(int i=0; i<=height.length;) {
 7             int curr = (i==height.length ? 0 : height[i]);
 8             if(stack.size() == 1 || curr > height[stack.peek()]) {
 9                 stack.push(i);
10                 i++;
11             } else {
12                 int index = stack.pop();
13                 maxArea = Math.max((i-stack.peek()-1)*height[index], maxArea);
14             }
15         }
16         return maxArea;
17     }

 

posted on 2015-03-17 23:16  linxiong1991  阅读(121)  评论(0编辑  收藏  举报

导航