题解 | #接雨水问题#

接雨水问题

http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f

双指针往中间移动,若lmax>rmax则hi--,否则lo++

#
# max water
# @param arr int整型一维数组 the array
# @return long长整型
#
class Solution:
    def maxWater(self , arr ):
        # write code here
        n = len(arr)
        if n <= 3:
            return 0
        lo, hi = 0, n-1
        lmax = arr[lo]
        rmax = arr[hi]
        ans = 0
        while lo <= hi:            
            lmax = max(lmax, arr[lo])            
            rmax = max(rmax, arr[hi])
            if lmax > rmax:
                ans += rmax-arr[hi]
                hi -= 1
            else:
                ans += lmax-arr[lo]
                lo += 1
        return ans
全部评论

相关推荐

06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务