计算蓝色部分(积水)面积
Trapping Rain Water
class Solution:
def maxArea(self, height):
area_list = []
l = len(height)
if l <= 1:
return 0
x = 0
y = l - 1
pointer = {'left_max':height[x], 'right_max':height[y]}
def calc(x, y):
# print('x, y:', x, y)
if x >= y:
return 0
area = 0
nextx = x
nexty = y
if height[x] < height[y]:
nextx = x + 1
area = pointer['left_max'] - height[nextx]
if area > 0:
area_list.append(area)
else:
pointer['left_max'] = height[nextx]
calc(nextx, nexty)
else:
nexty = y - 1
area = pointer['right_max'] - height[nexty]
if area > 0:
area_list.append(area)
else:
pointer['right_max'] = height[nexty]
calc(nextx, nexty)
calc(x, y)
# print('area_list:', area_list)
r = sum(area_list)
return r
height = [1,8,6,2,5,4,8,3,7]
# height = [3, 0,2,9]
print(Solution().maxArea(height))
网友评论