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 heights = [2,1,5,6,2,3],
return 10.

思路1:brute force 暴露破解法。(注意数值可能为0的情况)。

    遍历数组每一个元素,以改元素为起点向右遍历,求以该元素为起点的面积最大值。

 1 public class Solution {
 2     /**
 3      * @param height: A list of integer
 4      * @return: The area of largest rectangle in the histogram
 5      */
 6     public int largestRectangleArea(int[] height) {
 7         if (height == null || height.length == 0) {
 8             return 0;
 9         }
10         int maxArea = 0;
11         for (int i = 0; i < height.length; i++) {
12             int min = height[i];
13             maxArea = Math.max(maxArea, min);
14             for (int j = i + 1; j < height.length && height[j] != 0; j++) {
15                 min = Math.min(min, height[j]);
16                 maxArea = Math.max(maxArea, min * (j - i + 1));
17             }
18         }
19         return maxArea;
20     }
21 }

 Evolution : 可以发现如果height[i] < height[i - 1] , 那么 以height[i] 为起点的面积一定小于以height[i - 1] 为起点的面积,因此可以进行减枝操作。

 1 public class Solution {
 2     public int largestRectangleArea(int[] heights) {
 3         if (heights == null || heights.length == 0) {
 4             return 0;
 5         }
 6         int maxArea = 0;
 7         for (int i = 0; i < heights.length; i++) {
 8             if (i > 0 && heights[i] < heights[i - 1]) {
 9                 continue;
10             }
11             int min = heights[i];
12             maxArea = Math.max(maxArea, min);
13             for (int j = i + 1; j < heights.length && heights[j] != 0; j++) {
14                 min = Math.min(min, heights[j]);
15                 maxArea = Math.max(maxArea, min * (j - i + 1));
16             }
17         }
18         return maxArea;
19     }
20 }

 

posted @ 2016-04-07 10:05  YuriFLAG  阅读(153)  评论(0)    收藏  举报