Skip to content

Commit b0f4a25

Browse files
committed
Improved space complexity to O(1) by using two pointers approach
1 parent a051ab5 commit b0f4a25

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

dynamic_programming/trapped_water.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -34,23 +34,23 @@ def trapped_rainwater(heights: tuple[int, ...]) -> int:
3434
return 0
3535
if any(h < 0 for h in heights):
3636
raise ValueError("No height can be negative")
37-
length = len(heights)
38-
39-
left_max = [0] * length
40-
left_max[0] = heights[0]
41-
for i, height in enumerate(heights[1:], start=1):
42-
left_max[i] = max(height, left_max[i - 1])
43-
44-
right_max = [0] * length
45-
right_max[-1] = heights[-1]
46-
for i in range(length - 2, -1, -1):
47-
right_max[i] = max(heights[i], right_max[i + 1])
48-
49-
return sum(
50-
min(left, right) - height
51-
for left, right, height in zip(left_max, right_max, heights)
52-
)
53-
37+
left,right=0,len(heights)-1
38+
leftmax,rightmax=0,0
39+
water=0
40+
while left <right:
41+
if heights[left] < heights[right]:
42+
if heights[left] >= leftmax:
43+
leftmax=heights[left]
44+
else:
45+
water+=leftmax - heights[left]
46+
left+=1
47+
else:
48+
if heights[right] >= rightmax:
49+
rightmax=heights[right]
50+
else:
51+
water+=rightmax - heights[right]
52+
right-=1
53+
return water
5454

5555
if __name__ == "__main__":
5656
import doctest

0 commit comments

Comments
 (0)