[Python手撕]接雨水

Duancf發表於2024-09-05
class Solution:
    def trap(self, height: List[int]) -> int:

        n = len(height)

        pre = [0]*n
        post = [0]*n

        max_pre = 0
        max_post = 0

        for i in range(n):
            pre[i] = max_pre
            max_pre = max(max_pre,height[i])

        for i in range(n-1,-1,-1):
            post[i] = max_post
            max_post = max(max_post,height[i])
        
        count = 0
        for i in range(1,n-1):
            if min(pre[i],post[i]) >height[i]:
                count += min(pre[i],post[i]) - height[i]
        
        return count

相關文章