42. Trapping Rain Water
Approach 1: Brute Force
class Solution:
def trap(self, heights):
"""
:type height: List[int]
:rtype: int
"""
ans = 0
max_left, max_right = 0,0
for index, height in enumerate(heights):
ans += min(max(heights[:index+1]), max(heights[index:])) - height
return ansApproach 2: Memoise max
class Solution:
def trap(self, heights):
"""
:type height: List[int]
:rtype: int
"""
if len(heights) == 0:
return 0
ans = 0
l, r = 0, len(heights) - 1
ma_l, ma_r = heights[l], heights[r]
while l < r:
ma_l, ma_r = max(heights[l], ma_l), max(heights[r], ma_r)
if ma_l <= ma_r:
ans += ma_l - heights[l]
l += 1
else:
ans += ma_r - heights[r]
r -= 1
return ansLast updated