Trapping Rain Water(Leet Code Problem)


Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105

Following is sample python code.

def trap(height):
n = len(height)
left = 0
right = n - 1
left_max = right_max = trapped_water = 0

while left < right:
    if height[left] < height[right]:
        if height[left] >= left_max:
            left_max = height[left]
        else:
            trapped_water += left_max - height[left]
        left += 1
    else:
        if height[right] >= right_max:
            right_max = height[right]
        else:
            trapped_water += right_max - height[right]
        right -= 1

return trapped_water

height = [4, 2, 0, 3, 2, 5]
print(trap(height))