leecode练习 直方图的水量

给定一个直方图(也称柱状图),假设有人从上面源源不断地倒水,最后直方图能存多少水量?直方图的宽度为 1。

leecode练习 直方图的水量_第1张图片

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的直方图,在这种情况下,可以接 6 个单位的水(蓝色部分表示水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

题解

class Solution:
    def trap(self, height: List[int]) -> int:
        length = len(height)
        contain = 0
        for i in range(length):
            if i == 0:
                next
            elif i == length-1:
                next
            else:
                left_max = max(height[:i])
                right_max = max(height[i:])
                contain_now = 0 if height[i]>= min(left_max,right_max) else min(left_max,right_max)-height[i]
                contain = contain + contain_now
        return contain

你可能感兴趣的:(算法,leetcode)