nathanwailes

LeetCode 42 - Trapping Rain Water - 2022.12.30 solution - two pointers

Dec 30th, 2022
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. class Solution:
  2.     def trap(self, height: List[int]) -> int:
  3.         """ How to solve it: We're going to try to implement the O(1) memory two-pointer
  4.        solution.  So we don't need a result array, we just need an integer tracking the
  5.        amount of trapped water.  We're then going to step inwards from the left and
  6.        right, and whichever side has the smaller max height from that side, that will
  7.        be the side we will add to the water, and then step inwards from that side.
  8.        """
  9.         l = 0
  10.         r = len(height) - 1
  11.         water = 0
  12.         max_l_height = 0
  13.         max_r_height = 0
  14.  
  15.         while l <= r:
  16.             if max_l_height <= max_r_height:
  17.                 water += max(0, max_l_height - height[l])
  18.                 max_l_height = max(max_l_height, height[l])
  19.                 l += 1
  20.             else:
  21.                 water += max(0, max_r_height - height[r])
  22.                 max_r_height = max(max_r_height, height[r])
  23.                 r -= 1
  24.         return water
  25.    
Advertisement
Add Comment
Please, Sign In to add comment