Trapping Rain Water in Python

class Solution:
    def trap(self, height: List[int]) -> int:
        """
        This function computes how much water can be trapped after raining, given an elevation map represented by an array.

        :param height: List[int], a list of non-negative integers representing the elevation map.
        :return: int, the total amount of trapped rainwater.

        The function implements the optimized approach using two additional arrays to store the highest bar to the left
        and right of each bar in the elevation map.
        """

        if not height:
            return 0

        n = len(height)
        # Initializing left_max and right_max arrays
        left_max = [0] * n
        right_max = [0] * n

        # Fill the left_max array
        left_max[0] = height[0]
        for i in range(1, n):
            left_max[i] = max(left_max[i - 1], height[i])

        # Fill the right_max array
        right_max[n - 1] = height[n - 1]
        for i in range(n - 2, -1, -1):
            right_max[i] = max(right_max[i + 1], height[i])

        # Calculate the total amount of trapped water
        trapped_water = 0
        for i in range(n):
            # The trapped water at each bar is the minimum of the highest bars on either side minus the current bar's height
            trapped_water += min(left_max[i], right_max[i]) - height[i]

        return trapped_water

PrevNext