题目:接雨水
给定 n
个非负整数表示每个宽度为 1
的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
图例:
思路:从左到右找到每个位置的左侧最大值,从右往左找到每个位置的右侧最大值,2个值取最小然后减去当前位置的柱子高度即为当前位置的可接雨水的量。
代码:
class Solution:
def trap(self, height: List[int]) -> int:
curr_left = [0] * len(height)
max_left = 0
for i in range(len(height)):
max_left = max(max_left, height[i])
curr_left[i] = max_left
print(curr_left)
cur_right = [0] * len(height)
max_right = 0
for j in range(len(height) - 1, -1, -1):
max_right = max(max_right, height[j])
cur_right[j] = max_right
result = []
for i in range(len(height)):
result.append(min(cur_right[i], curr_left[i]) - height[i])
# print(result)
return sum(result)