[leetcode] Largest Rectangle in Histogram

來源:互聯網
上載者:User

標籤: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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.