编程语言
首页 > 编程语言> > python-直方图中矩形的最大面积-为什么需要堆栈?

python-直方图中矩形的最大面积-为什么需要堆栈?

作者:互联网

考虑以下problem (and solution)

Given n non-negative integers representing the height of bars of width one of a histogram, find the maximum area rectangle of histogram i.e. the maximum area rectangle contained in the histogram.

关键思想是计算:

R[i] = Area of the largest rectangle with the bar at i is as the
smallest bar in the rectangle (i.e. width = H[i]) left[i] = the left
most boundary of R[i], which is the leftmost bar greater than H[i].
right[i] = the right most boundary of R[i], which is the rightmost bar
greater than H[i].

我知道需要一个堆栈来计算左右,但我认为我无需使用堆栈就可以提供类似的解决方案:

def max_area_rect(lst):
    n = len(lst)
    right = [-1] * n
    left = [-1] * n

    right[n - 1] = n
    for i in range(n - 2, -1, -1):
        right[i] = i + 1 if lst[i] > lst[i + 1] else right[i + 1]

    left[0] = -1
    for i in range(1, n):
        left[i] = i - 1 if lst[i - 1] < lst[i] else left[i - 1]

    max_res = -1
    for i in range(n):
        right_len = right[i] - i -1
        left_len = i - left[i] + 1
        h = min(lst[right_len - 1], lst[left_len + 1])
        res = (right_len + left_len) * h
        if res > max_res:
            max_res = res

    return max_res

    # test
    print(max_area_rect([4, 2, 1, 8, 6, 8, 5, 2])) # expected result: 20

所以我的问题是:为什么我们需要堆栈?我的方式有效吗?

解决方法:

如前所述,left [i]的定义

left[i] = the left most boundary of R[i], which is the leftmost bar greater than H[i]

您在代码中定义的内容

left[i] = i - 1 if lst[i - 1] < lst[i] else left[i - 1]

即,如果左侧的栏更高,则表示您将left [i] = left [i-1].但是,这里的错误是left [i-1]存储的最左索引大于lst [i-1]而不是lst [i].

例如,在您输入的序列中的序列6、8、5中,left [i] for 8不应该包含6,所以left [i]应该是i,但是left [i] for 5应该包含6和8以及那是什么?您的代码被忽略.

标签:computer-science,python,algorithm
来源: https://codeday.me/bug/20191109/2010745.html