Trapping Rain Water

T: O(n)
Feedback

Trapping Rain Water

Move left (idx 0). Water here: 0. Total: 0.
Heights & trapped water
0
0
1
1
0
2
2
3
1
4
0
5
1
6
3
7
2
8
1
9
2
10
1
11
Total water: 0
leftright
SpeedNormal (500ms)
Parameters

{ height: number[] }

Variables
left0
right11
leftMax0
rightMax0
water0
1left = 0, right = 11 (n = 12)
2leftMax = 0, rightMax = 0, water = 0
3while left < right:
4 if height[left] <= height[right]: → 0 <= 1
5 leftMax = max(leftMax, height[left])
6 water += leftMax - height[left]
7 left++
8 else:
9 rightMax = max(rightMax, height[right])
10 water += rightMax - height[right]
11 right--
12return water
Output
Move left (idx 0). Water here: 0. Total: 0.