-
Notifications
You must be signed in to change notification settings - Fork 612
/
42.py
31 lines (28 loc) · 845 Bytes
/
42.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'''
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
'''
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
left, right = 0, len(height) - 1
leftMax, rightMax = 0, 0
result = 0
while left < right:
if height[left] < height[right]:
if height[left] > leftMax:
leftMax = height[left]
else:
result += (leftMax - height[left])
left += 1
else:
if height[right] > rightMax:
rightMax = height[right]
else:
result += (rightMax - height[right])
right -= 1
return result