nathanwailes

LeetCode 42 - Trapping Rain Water - 2022.12.29 solution

Dec 29th, 2022
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. class Solution:
  2.     def trap(self, height: List[int]) -> int:
  3.         """ How to solve it: To solve it in O(n) time complexity, we want to think about
  4.        what information we need at each index to be able to answer the question for
  5.        that index.  In this case, the amount of water trapped at each index is
  6.        determined by the lesser of the maximum height to the left of the position and
  7.        the maximum height to the right of the position.  So we could think to first
  8.        construct two other lists, one containing the max height to the left of each
  9.        index, the other containing the max height to the right of each index.  But we
  10.        don't actually need the second one, because we can calculate the answer during
  11.        the same pass through the input that we would've used to populate that list,
  12.        simply maintaining a single variable ('max_height_to_the_right').  And we could
  13.        use the same list used to store the max-height-to-the-left for our output.
  14.        """
  15.         if len(height) < 3:
  16.             return 0
  17.        
  18.         # Fill out the max-height-to-the-left-of-this-index list.
  19.         res = [0 for i in range(len(height))]
  20.         res[0] = 0
  21.         res[1] = height[0]
  22.         for i in range(2, len(height)):
  23.             res[i] = max(res[i-1], height[i-1])
  24.        
  25.         # Pass from right-to-left through the input
  26.         max_height_to_the_right = 0
  27.         for i in range(len(height) - 1, -1, -1):
  28.             if i < len(height) - 1:
  29.                 max_height_to_the_right = max(max_height_to_the_right, height[i+1])
  30.            
  31.             # Calculate trapped water at i
  32.             min_of_two_max_heights = min(res[i], max_height_to_the_right)
  33.             res[i] = max(min_of_two_max_heights - height[i], 0)
  34.         return sum(res)
Advertisement
Add Comment
Please, Sign In to add comment