Skip to content

Commit 708876c

Browse files
committed
Resolved 'Trapping Rain Water' LeetCode problem with an optimized solution
1 parent 4d682bc commit 708876c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Python/trapping_rain_water.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Trapping Rain Water
2+
3+
class Solution(object):
4+
def trap(self, height):
5+
left, right = 0, len(height) - 1
6+
left_max = right_max = water_trapped = 0
7+
8+
while left < right:
9+
if height[left] <= height[right]:
10+
if height[left] > left_max:
11+
left_max = height[left]
12+
else:
13+
water_trapped += left_max - height[left]
14+
left += 1
15+
else:
16+
if height[right] > right_max:
17+
right_max = height[right]
18+
else:
19+
water_trapped += right_max - height[right]
20+
right -= 1
21+
22+
return water_trapped
23+
24+
solution = Solution()
25+
print(solution.trap([0,1,0,2,1,0,1,3,2,1,2,1]))

0 commit comments

Comments
 (0)