MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / trapped_rainwater

Function trapped_rainwater

dynamic_programming/trapped_water.py:16–52  ·  view source on GitHub ↗

The trapped_rainwater function calculates the total amount of rainwater that can be trapped given an array of bar heights. It uses a dynamic programming approach, determining the maximum height of bars on both sides for each bar, and then computing the trapped water above each bar.

(heights: tuple[int, ...])

Source from the content-addressed store, hash-verified

14
15
16def trapped_rainwater(heights: tuple[int, ...]) -> int:
17 """
18 The trapped_rainwater function calculates the total amount of rainwater that can be
19 trapped given an array of bar heights.
20 It uses a dynamic programming approach, determining the maximum height of bars on
21 both sides for each bar, and then computing the trapped water above each bar.
22 The function returns the total trapped water.
23
24 >>> trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1))
25 6
26 >>> trapped_rainwater((7, 1, 5, 3, 6, 4))
27 9
28 >>> trapped_rainwater((7, 1, 5, 3, 6, -1))
29 Traceback (most recent call last):
30 ...
31 ValueError: No height can be negative
32 """
33 if not heights:
34 return 0
35 if any(h < 0 for h in heights):
36 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
54
55if __name__ == "__main__":

Callers 1

trapped_water.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected