Created
March 31, 2022 17:24
-
-
Save ThomasHigginson/52c148723eb5fb3a6fedbe336b234c9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is the 2 pointer Solution/Approach | |
# It utilizes the fact that the amount of water a position | |
# can contain is bounded by the smallest wall to its left and right | |
# If the left < right, then we KNOW that it can contain whatever | |
# amount of water with respect to the height of the left wall (the smaller wall). | |
# and vice versa | |
def trap(self, height: List[int]) -> int: | |
leftMax, rightMax, ans = 0, 0, 0 | |
left, right = 0, len(height)-1 | |
while left < right: | |
if height[left] < height[right]: | |
if height[left] < leftMax: # Can contain water | |
ans += leftMax - height[left] | |
else: | |
leftMax = height[left] | |
left += 1 | |
else: # height[right] >= height[left] | |
if height[right] < rightMax: # Can contain water | |
ans += rightMax - height[right] | |
else: | |
rightMax = height[right] | |
right -= 1 | |
return ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment