@@ -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
5555if __name__ == "__main__" :
5656 import doctest
0 commit comments