Skip to content

Commit

Permalink
Trapping rain water solution - leetcode 42
Browse files Browse the repository at this point in the history
  • Loading branch information
GraniteMask committed Oct 26, 2022
1 parent ce83ba7 commit b5a7321
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions dp/Trapping Rain Water/trapping_rain_water_solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Optimal Solution - O(1) solution
class Solution:
def trap(self, height: List[int]) -> int:

if not height: return 0

l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0

while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
res += rightMax - height[r]
return res

# Try O(n) solution using arrays as memory

0 comments on commit b5a7321

Please # to comment.