Skip to content

Commit

Permalink
re-solve "42. Trapping Rain Water"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Sep 10, 2024
1 parent 8b36471 commit 607b3e7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
4 changes: 4 additions & 0 deletions .plan
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Sep 10, 2024

* re-solve "42. Trapping Rain Water"

Sep 9, 2024

solve all "array / string" questions in top-150
Expand Down
28 changes: 16 additions & 12 deletions src/trapping_rain_water.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
class Solution:
def trap(self, height: list[int]) -> int:
result = 0
total_water = 0

max_left, max_right = 0, 0
left, right = 0, len(height) - 1
max_left = height[0]
max_right = height[-1]

while left != right:
if height[left] <= height[right]:
result += max(0, max_left - height[left])
max_left = max(max_left, height[left])
left += 1
li, ri = 0, len(height) - 1

while ri - li > 1:
if max_left <= max_right:
water = min(max_left, max_right) - height[li + 1]
li += 1
max_left = max(max_left, height[li])
else:
result += max(0, max_right - height[right])
max_right = max(max_right, height[right])
right -= 1
water = min(max_left, max_right) - height[ri - 1]
ri -= 1
max_right = max(max_right, height[ri])

total_water += max(0, water)

return result
return total_water

0 comments on commit 607b3e7

Please sign in to comment.