File tree Expand file tree Collapse file tree 1 file changed +18
-1
lines changed
src/leetcode/hard/trapping-rain-water Expand file tree Collapse file tree 1 file changed +18
-1
lines changed Original file line number Diff line number Diff line change 22
22
23
23
24
24
def trap (heights : List [int ]) -> int :
25
- if isinstance (heights , list ):
25
+ """
26
+ Compute how much water can be trapped after raining.
27
+
28
+ Args:
29
+ heights (List[int]): A list of non-negative integers representing an elevation map.
30
+
31
+ Returns:
32
+ int: The amount of water that can be trapped.
33
+ """
34
+ # Edge case: input is not a list
35
+ if not isinstance (heights , list ):
26
36
raise TypeError ("Arguments must be of type list" )
37
+
38
+ # Edge case: empty list
27
39
if len (heights ) < 1 :
28
40
return 0
29
41
42
+ # Initialize variables to keep track of water trapped and maximum heights on both sides
30
43
water_trapped = 0
31
44
left = 0
32
45
right = len (heights ) - 1
33
46
max_left = heights [left ]
34
47
max_right = heights [right ]
35
48
49
+ # Loop through the list until the two pointers meet
36
50
while left < right :
51
+ # Move the pointer that points to the smaller maximum height
37
52
if max_left <= max_right :
38
53
left += 1
39
54
else :
40
55
right -= 1
41
56
57
+ # Update the trapped water and maximum heights for this iteration
42
58
current_index = left if max_left <= max_right else right
43
59
trapped = min (max_left , max_right ) - heights [current_index ]
44
60
water_trapped += trapped if trapped > 0 else 0
45
61
max_right = max (max_right , heights [right ])
46
62
max_left = max (max_left , heights [left ])
47
63
64
+ # Return the total amount of water that can be trapped
48
65
return water_trapped
You can’t perform that action at this time.
0 commit comments