nathanwailes

LeetCode 42 - Trapping Rain Water - 2023.10.11 solution

Oct 10th, 2023
1,262
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.         """ As you step through each index, to determine how much rain water is at
  4.        that location, what information do you want to know about the rest of the
  5.        array?  You want to know 1) what's the tallest index to the left, and 2)
  6.        what's the tallest index to the right.  Then you want to use the minimum of
  7.        those two numbers to determine the height of the 'walls', and then compare
  8.        it to the height at the current index to see how much water there is.
  9.  
  10.        So the plan is: first create two supplementary lists: one that, for each
  11.        index, keeps track of the tallest index to the left of that index, and a
  12.        second one that, for each index, keeps track of the tallest index to the
  13.        right of that index.
  14.        """
  15.         tallest_to_the_left = [0 for i in range(len(height))]
  16.         for i in range(len(height)):
  17.             if i == 0:
  18.                 continue
  19.             tallest_to_the_left[i] = max(tallest_to_the_left[i-1], height[i-1])
  20.        
  21.         tallest_to_the_right = [0 for i in range(len(height))]
  22.         for i in range(len(height)-1, -1, -1):
  23.             if i == len(height)-1:
  24.                 continue
  25.             tallest_to_the_right[i] = max(tallest_to_the_right[i+1], height[i+1])
  26.        
  27.         rain_water_at_each_index = [0 for i in range(len(height))]
  28.         for i in range(len(height)):
  29.             wall_height = min(tallest_to_the_left[i], tallest_to_the_right[i])
  30.             if height[i] < wall_height:
  31.                 rain_water_at_each_index[i] = wall_height - height[i]
  32.        
  33.         return sum(rain_water_at_each_index)
  34.  
Advertisement
Add Comment
Please, Sign In to add comment