[Python][LeetCode] 42. Trapping Rain Water
class Solution:
def trap(self, height: List[int]) -> int:
l = 0
r = len(height) - 1
# Those are for initializing
left_max_height = 0
right_max_height = 0
total_water = 0
while l < r:
if height[l] < height[r]: # Point 1. This is one of the 'any' condition
# just for checkiing all the elements for the list.
if left_max_height <= height[l]:
left_max_height = height[l]
else:
total_water += (left_max_height - height[l])
l += 1
else: ###### marking 1 (point 1's)
# Point 2. Basically, if the next index's height is 'higher' than before one,
# we just have to renew the variable of varialbe of 'right_max_height' and moving the index of 'r'.
if right_max_height <= height[r]:
right_max_height = height[r]
# Point3. Basically, if the next index's height is lower than before one,
# we have to add 'that difference' to variable of 'total_water'.
else:
total_water += (right_max_height - height[r])
r -= 1 ###### marking 2 (point 1's)
return total_water
Summary
-
while l < r: if height[l] < height[r]:
This is one of the ‘any’ condition just for checkiing all the elements for the list by moving index of ‘l’ and ‘r’. (Pay attention to the indentation! I marked them!)
-
if right_max_height <= height[r]: right_max_height = height[r]
Basically, if the next index’s height is ‘higher’ than before one, we just have to renew the variable of varialbe of ‘right_max_height’ and moving the index of ‘r’. (The case of ‘left’ is almost same with this.)
-
else: total_water += (right_max_height - height[r]) r -= 1
Basically, if the next index’s height is lower than before one, we have to add ‘that difference’ to variable of ‘total_water’.(The case of ‘left’ is almost same with this.)
댓글남기기