1def trap(heights):
2 left = 0
3 right = len(heights) - 1
4 leftMax = 0
5 rightMax = 0
6 water = 0
7
8 while left < right:
9 if heights[left] < heights[right]:
10 if heights[left] >= leftMax:
11 leftMax = heights[left]
12 else:
13 water += leftMax - heights[left]
14 left += 1
15 else:
16 if heights[right] >= rightMax:
17 rightMax = heights[right]
18 else:
19 water += rightMax - heights[right]
20 right -= 1
21
22 return water