美文网首页
台阶积水(Trapping Rain Water)

台阶积水(Trapping Rain Water)

作者: 心阅万物 | 来源:发表于2019-11-12 21:51 被阅读0次

计算蓝色部分(积水)面积


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))

相关文章

网友评论

      本文标题:台阶积水(Trapping Rain Water)

      本文链接:https://www.haomeiwen.com/subject/cfkcictx.html