Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def trap(self, height: List[int]) -> int:
- """ How to solve it: We're going to try to implement the O(1) memory two-pointer
- solution. So we don't need a result array, we just need an integer tracking the
- amount of trapped water. We're then going to step inwards from the left and
- right, and whichever side has the smaller max height from that side, that will
- be the side we will add to the water, and then step inwards from that side.
- """
- l = 0
- r = len(height) - 1
- water = 0
- max_l_height = 0
- max_r_height = 0
- while l <= r:
- if max_l_height <= max_r_height:
- water += max(0, max_l_height - height[l])
- max_l_height = max(max_l_height, height[l])
- l += 1
- else:
- water += max(0, max_r_height - height[r])
- max_r_height = max(max_r_height, height[r])
- r -= 1
- return water
Advertisement
Add Comment
Please, Sign In to add comment