gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:13:05 26 4
gpt4 key购买 nike

考虑以下 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].

我知道需要一个堆栈来计算 rightleft我认为我能够提供类似的解决方案而无需使用堆栈:

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] 8 不应包含 6,所以 left[i] 应该是 ileft[i] 5 应该包括 68 这就是您的代码忽略的内容。

关于python - 直方图中矩形的最大面积 - 为什么我们需要堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50560882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com