Trapping Rain Water

Trapping Rain Water

O(1) Version - 44ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left = right = water = 0
i, j = 0, len(height) - 1
while i <= j:
left, right = max(left, height[i]), max(right, height[j])
while i <= j and height[i] <= left <= right:
water += left - height[i]
i += 1
while i <= j and height[j] <= right <= left:
water += right - height[j]
j -= 1
return water

test code

1
2
3
4
In [36]: s = Solution(); t = s.trap([0,1,0,2,1,0,1,3,2,1,2,1])
In [37]: t
Out[37]: 6

leet code