42. Trapping Rain Water

Question

CleanShot 2024-09-26 at 20.14.29.png

Code

class Solution(object):
    def trap(self, height):
        l, r = 0, len(height) - 1
        l_height, r_height = height[l], height[r]
        total = 0

        while l < r:
            if l_height < r_height:
                l += 1
                if l_height - height[l] > 0:
                    total += l_height - height[l]
                l_height = max(l_height, height[l])
            else:
                r -= 1
                if r_height - height[r] > 0:
                    total += r_height - height[r]
                r_height = max(r_height, height[r])

        return total

CleanShot 2024-03-13 at 09.26.29.png