GivenNNon-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]
,
Return10
.
Https://oj.leetcode.com/problems/largest-rectangle-in-histogram/
Idea 1: The left and right boundary is not supported. O (N ^ 2) is too slow.
Idea 2: For the solution, see reference 2. Complexity O (n ).
The reason for this algorithm is correct: For details, see reference 1. My understanding is like this: what we need to do is for any bar 'x ', we need to calculate the largest rectangle that can be formed with X as the height. To calculate the maximum rectangle with X as the height, we need to find the first shorter position on the left and the shorter position on the right to calculate the width of the rectangle. For this clever method of using Stack, when a bar is decreasing, we pop and calculate the largest rectangle with this bar as the height. The bar that is encountering a decreasing bar is the right boundary, the left boundary is the element at the top of the stack.
public class Solution { public int largestRectangleArea(int[] height) { Stack<Integer> stack = new Stack<Integer>(); int maxArea = 0; for (int i = 0; i < height.length;) { if (stack.isEmpty() || height[i] >= height[stack.peek()]) { stack.push(i++); } else { int start = stack.pop(); int width = stack.isEmpty() ? i : (i - stack.peek() - 1); maxArea = Math.max(maxArea, height[start] * width); } } while (!stack.isEmpty()) { int start = stack.pop(); int width = stack.isEmpty() ? height.length : (height.length - stack.peek() - 1); maxArea = Math.max(maxArea, height[start] * width); } return maxArea; } public static void main(String[] args) { System.out.println(new Solution().largestRectangleArea(new int[] { 2, 1, 5, 6, 2, 3 })); }}
View code
Refer:
Http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
Http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html#2973562
Http://blog.csdn.net/linhuanmars/article/details/20524507