【问题标题】:Maximum Area Rectangle In Histogram. Find dimensions of the Max Rectangle直方图中的最大面积矩形。查找最大矩形的尺寸
【发布时间】:2018-03-13 05:00:18
【问题描述】:

我正在尝试查找最大面积直方图,但我想跟踪最大矩形的高度和宽度。我通过初始化和跟踪全局宽度尝试了不同的方法,但无法做到。

这是我写的最大面积直方图的代码。 使用此视频进行编码。 https://www.youtube.com/watch?v=RVIh0snn4Qc&t=888s

class Solution:
def largestRectangleArea(self, hist):
    stack=[]; i=0; area=0
    while i<len(hist):
        if stack==[] or hist[i]>hist[stack[len(stack)-1]]:
            stack.append(i)
        else:
            curr=stack.pop()
            width=i if stack==[] else i-stack[len(stack)-1]-1
            area=max(area,width*hist[curr])
            i-=1
        i+=1
    while stack!=[]:
        curr=stack.pop()
        width=i if stack==[] else len(hist)-stack[len(stack)-1]-1

        area=max(area,width*hist[curr])
    return area, 

def maximalRectangle(self, matrix):
    if matrix==[]: return 0
    a=[0 for i in range(len(matrix[0]))]; maxArea=0
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            a[j]=a[j]+1 if matrix[i][j]=='1' else 0

        maxArea=max(maxArea, self.largestRectangleArea(a)[0])
        print (self.largestRectangleArea(a))
    return maxArea


if __name__ == "__main__":
print( Solution().maximalRectangle([['1', '1', '0', '1', '0', '1'],
                                    ['0', '1', '0', '0', '1', '1'],
                                    ['1', '1', '1', '1', '0', '1'],
                                    ['1', '1', '1', '1', '0', '1']]))

【问题讨论】:

    标签: python algorithm data-structures dynamic-programming


    【解决方案1】:

    用自己的实现替换内置的max 操作——当你得到更好的结果时,记住widthhist[curr]) 的值是最好的(在那一刻)。像这样:

      #area=max(area,width*hist[curr])
      newarea = width*hist[curr] 
      if (newarea>area):
            area = newarea
            bestw = width
            besth = hist[curr]
    

    【讨论】:

    • 谢谢。我犯了一个愚蠢的错误。我在 while 循环中打印宽度。
    猜你喜欢
    • 2018-04-01
    • 2010-09-05
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多