zoukankan      html  css  js  c++  java
  • [LC] 84. 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.

    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
  • 相关阅读:
    数据库之表与表之间的关系
    数据库之完整性约束条件
    基本数据类型
    数据库
    Django ajax 发送post请求 前端报错解决
    Django数据库建立注意事项
    编程单词汇总
    程序员必掌握600单词
    python思维导图
    用jQuery模拟hover选择效果
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11828789.html
Copyright © 2011-2022 走看看