trapping rain water

Go Back home
1 def trap(height):
2     l, r, level, water = 0, len(height)-1, 0, 0
3     while l < r:
4         lev_i, l, r = (l, l+1, r) if height[l] < height[r] else (r, l, r-1)
5         level = max(level, height[lev_i])
6         water += level - height[lev_i]
7     return water
8 
9 print(trap([0,1,0,2,1,0,1,3,2,1,2,1]))

See also:

max array
max array from right