def rain_water(heights): # Initialize two pointers at the leftmost and rightmost positions of the elevation map left = 0 right = len(heights) - 1 # Variables to store the accumulated rainwater and maximum heights stored_water = 0 left_max, right_max = 0, 0 while left <= right: # If the maximum height on the right is less than or equal to the maximum height on the left if left_max > right_max: stored_water += max(0, right_max - heights[right]) # Update the right maximum height if necessary right_max = max(right_max, heights[right]) right -= 1 # If the maximum height on the left is less than the maximum height on the right else: stored_water += max(0, left_max - heights[left]) # Update the left maximum height if necessary left_max = max(left_max, heights[left]) left +=1 return stored_water # Driver code def main(): input_list = [ [1, 0, 1, 2, 1, 4, 0, 3, 5], [2, 0, 9, 6], [3, 1, 2, 0, 2], [4, 2, 5, 3], [3, 0] ] index = 1 for i in input_list: print(str(index)+".\tHeights: "+str(i)) print("\tMaximum rainwater: " + str(rain_water(i))) index += 1 print("-" * 100) if __name__ == "__main__": main()