Created
October 19, 2017 15:42
-
-
Save cixuuz/cd4159bf4d1b5d31fa27f13062e1681b to your computer and use it in GitHub Desktop.
[42. Trapping Rain Water] #leetcode
This file contains hidden or 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
class Solution(object): | |
def trap(self, height): | |
""" | |
:type height: List[int] | |
:rtype: int | |
""" | |
# return placeholder | |
res = 0 | |
# corner case | |
if not height or len(height) <= 2: | |
return res | |
# initialize data | |
left, right, leftmax, rightmax = 0, len(height) - 1, 0, 0 | |
# two points from left and from right respectively | |
while left <= right: | |
# find the left or right bound and get the trapped water | |
if leftmax <= rightmax: | |
res += max(leftmax - height[left], 0) | |
leftmax = max(leftmax, height[left]) | |
left += 1 | |
else: | |
res += max(rightmax - height[right], 0) | |
rightmax = max(rightmax, height[right]) | |
right -= 1 | |
# print("{} {} {} {} {}".format(left, right, leftmax, rightmax, res)) | |
# return | |
return res | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment