码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 84. Largest Rectangle in Histogram

时间:2019-11-10 10:13:49      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:rectangle   style   present   sha   dex   width   pop   show   nbsp   

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.

 

Example:

Input: [2,1,5,6,2,3]
Output: 10

Solution 1: O(N^2) LTE
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        if not heights:
            return 0
        res = -1
        for i, height in enumerate(heights):
            min_height = height
            res = max(res, min_height)
            for j in range(i + 1, len(heights)):
                min_height = min(min_height, heights[j])
                res = max(res, (j - i + 1) * min_height)
        return res

 

Solution 2: O(N)

 class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        if not heights:
            return 0
        res, index  = 0, 0
        stack = []
        while index <= len(heights):
            cur = 0 if index == len(heights) else heights[index]
            if not stack or cur >= heights[stack[-1]]:
                stack.append(index)
                index += 1
            else:
                height = heights[stack.pop()]
                # make sure left and right index are correct
                right = index - 1
                left = 0 if not stack else stack[-1] + 1
                res = max(res, (right - left + 1) * height)
        return res

 

 

[LC] 84. Largest Rectangle in Histogram

标签:rectangle   style   present   sha   dex   width   pop   show   nbsp   

原文地址:https://www.cnblogs.com/xuanlu/p/11828789.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!