nathanwailes

LeetCode 42 - Trapping Rain Water - 2023.04.02 solution

Apr 2nd, 2023
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. class Solution:
  2.     def trap(self, height: List[int]) -> int:
  3.         """ To solve this, we want to understand how to calculate the amount of rainwater
  4.        trapped at each index.  Then we just need to have that information that's necessary
  5.        to do that calculation.
  6.  
  7.        The calculation is that the amount of water is defined by the difference between
  8.        the (minimum of the max height to the left and right of the point) and the height
  9.        of the current index.
  10.  
  11.        So if we're going to visit each index once to do the calculation, we first need to
  12.        know the max heights to the left and right of each point.  We can do that in two
  13.        other passes.
  14.  
  15.        So first we'll go through and create a list of the max height to the left of each
  16.        point, then a second time backwards to create a list of the max height to the right
  17.        of each point, and then a final time to do the calculation.
  18.        """
  19.         max_height_to_the_l = [0 for h in height]
  20.         for i, h in enumerate(height):
  21.             if i == 0:
  22.                 continue
  23.             max_height_to_the_l[i] = max(height[i-1], max_height_to_the_l[i-1])
  24.        
  25.         max_height_to_the_r = [0 for h in height]
  26.         for i in range(len(height)-2, -1, -1):
  27.             h = height[i]
  28.             max_height_to_the_r[i] = max(height[i+1], max_height_to_the_r[i+1])
  29.        
  30.         water_at_each_index = [0 for h in height]
  31.         for i in range(len(height)):
  32.             brim_level = min(max_height_to_the_l[i], max_height_to_the_r[i])
  33.             water_at_each_index[i] = max(0, brim_level - height[i])
  34.        
  35.         return sum(water_at_each_index)
Advertisement
Add Comment
Please, Sign In to add comment