Skip to content

Commit daeccc0

Browse files
committed
Do water question
1 parent b74b700 commit daeccc0

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

my-submissions/h42 v1 heap.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def trap(self, height: List[int]) -> int:
3+
output = 0
4+
5+
vals = [(-x, i) for i, x in enumerate(height)]
6+
heapify(vals)
7+
8+
left_max = right_max = heappop(vals)[1]
9+
while vals and (left_max > 0 or right_max < len(height) - 1):
10+
val, i = heappop(vals)
11+
val = -val
12+
13+
if left_max <= i <= right_max :
14+
continue
15+
16+
if i <= left_max :
17+
minn = min(val, height[left_max])
18+
output += sum(minn - x for x in height[i + 1:left_max])
19+
left_max = i
20+
else :
21+
minn = min(val, height[right_max])
22+
output += sum(minn - x for x in height[right_max + 1:i])
23+
right_max = i
24+
25+
return output
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def trap(self, height: List[int]) -> int:
3+
left_max = right_max = output = 0
4+
left, right = 0, len(height) - 1
5+
6+
while left < right :
7+
if height[left] < height[right] :
8+
output += (left_max := max(left_max, height[left])) - height[left]
9+
left += 1
10+
else :
11+
output += (right_max := max(right_max, height[right])) - height[right]
12+
right -= 1
13+
14+
return output

0 commit comments

Comments
 (0)