標籤:style blog http color width os
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.
https://oj.leetcode.com/problems/largest-rectangle-in-histogram/
思路1:窮舉左右邊界,O(n^2),太慢。
思路2:解法見參考2。複雜度 O(n)。
該演算法正確的原因:詳見參考1,我的理解大概是這樣:我們要做的是,對於任意的一個bar ‘x‘,我們需要計算以x為高度能形成的最大矩形。為了計算以x為高度的最大矩形,我們需要找到左邊第一個比x矮的位置和右邊一的哥比x矮的位置來計算這個矩形的寬度。對於這個用stack的巧妙解法,當遇到遞減的bar時,我們pop並計算以這個bar為高度的最大矩形,遇到的遞減的bar就是右邊界,而左邊界就是棧頂的元素。
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
參考:
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