-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0042-trapping-rain-water.py
More file actions
29 lines (24 loc) · 794 Bytes
/
0042-trapping-rain-water.py
File metadata and controls
29 lines (24 loc) · 794 Bytes
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
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
ans = 0
left, right = 0, len(height) - 1
leftMax, rightMax = 0, 0
while left < right:
if height[left] < height[right]:
if height[left] >= leftMax:
leftMax = height[left]
else:
ans += leftMax - height[left]
left += 1
else:
if height[right] >= rightMax:
rightMax = height[right]
else:
ans += rightMax - height[right]
right -= 1
return ans
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
print(Solution().trap(height))