42. Trapping Rain Water
Question
Code
- set the boundary first, compare constantly to the min of left max and right max
class Solution(object):
def trap(self, height):
l, r = 0, len(height) - 1
l_height, r_height = height[l], height[r]
total = 0
while l < r:
if l_height < r_height:
l += 1
if l_height - height[l] > 0:
total += l_height - height[l]
l_height = max(l_height, height[l])
else:
r -= 1
if r_height - height[r] > 0:
total += r_height - height[r]
r_height = max(r_height, height[r])
return total