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
.
算法分析:有两种方法,第一种暴力法,利用两重循环,求[i,j]之间最大的矩形面积。第二种方法利用栈,栈中存放递增的索引。
方法一:brute force
//brute force,用两重循环,求[i,j]之间最小值 public static int largestRectangleArea(int[] heights) { int minHeight = 0; int maxArea = 0; for(int i = 0; i < heights.length; i ++) { for(int j = i; j < heights.length; j ++) { if(i == j) { minHeight = heights[i]; } else { if(heights[j] < minHeight) { minHeight = heights[j]; } } int temp = minHeight * (j - i + 1); if(maxArea < temp) { maxArea = temp; } } } return maxArea; }
方法二:http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
//利用栈和单调性 public static int largestRectangleArea2(int[] heights) { Stack<Integer> stack = new Stack<>(); int[] h = Arrays.copyOf(heights, heights.length + 1);//h最后元素补0,为了让所有元素出栈,所以补0 int i = 0; int maxArea = 0; while(i < h.length) { if(stack.isEmpty() || h[stack.peek()] <= h[i]) { stack.push(i++);//只存放单调递增的索引 } else { int t = stack.pop();//stack.isEmpty说明i是栈里最小的元素,面积为i*h[t] maxArea = Math.max(maxArea, h[t]*(stack.isEmpty() ? i : i-stack.peek()-1)); } } return maxArea; }