Skip to content

Commit 5c09392

Browse files
committed
041 Trapping Rain Water
1 parent f5ab752 commit 5c09392

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

041 Trapping Rain Water py3.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given n non-negative integers representing an elevation map where the width of
4+
each bar is 1, compute how much water it is able to trap after raining.
5+
6+
7+
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In
8+
this case, 6 units of rain water (blue section) are being trapped.
9+
10+
Example:
11+
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
12+
Output: 6
13+
"""
14+
15+
class Solution:
16+
def trap(self, height: List[int]) -> int:
17+
"""
18+
At each position, the water is determined by the left and right max
19+
20+
Let lefts[i] be the max(height[:i])
21+
Let rights[i] be the max(height[i:])
22+
"""
23+
n = len(height)
24+
lefts = [0 for _ in range(n+1)]
25+
rights = [0 for _ in range(n+1)]
26+
for i in range(1, n+1): # i, index of lefts
27+
lefts[i] = max(lefts[i-1], height[i-1])
28+
for i in range(n-1, -1, -1):
29+
rights[i] = max(rights[i+1], height[i])
30+
31+
ret = 0
32+
for i in range(n):
33+
ret += max(
34+
0,
35+
min(lefts[i], rights[i+1]) - height[i]
36+
)
37+
return ret

0 commit comments

Comments
 (0)