From 607b3e74cc7b5a59e17fbbfff4a92fcdb946e5ad Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Tue, 10 Sep 2024 18:39:08 +0200 Subject: [PATCH] re-solve "42. Trapping Rain Water" --- .plan | 4 ++++ src/trapping_rain_water.py | 28 ++++++++++++++++------------ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/.plan b/.plan index 1201720..69965e8 100644 --- a/.plan +++ b/.plan @@ -1,3 +1,7 @@ +Sep 10, 2024 + +* re-solve "42. Trapping Rain Water" + Sep 9, 2024 solve all "array / string" questions in top-150 diff --git a/src/trapping_rain_water.py b/src/trapping_rain_water.py index b00d31c..58acdfb 100644 --- a/src/trapping_rain_water.py +++ b/src/trapping_rain_water.py @@ -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