describe
Given an integer arrayarr**, all the The values are all non-negative. Think of this array as a column height map, and calculate how much rain the columns arranged in this way can catch after it rains. (The height of the area outside the array is regarded as0)**
Number of units: Number of units of length** 0≤n≤2×10^5^,Number of pairs per unit is full 0<val≤10^9^ 0≤val≤10^9^ **,guaranteed return result complete
Sample
enter
3,1,2,5,2,4
output
5
Code:
height = [int(x) for x in input().split(',')]
n = len(height)
left, right = 0, n - 1
left_max, right_max = height[0], height[n - 1]
summ = 0
while left <= right:
left_max = max(left_max, height[left])
right_max = max(right_max, height[right])
if left_max < right_max:
summ += left_max - height[left]
left += 1
else:
summ += right_max - height[right]
right -= 1
print(summ)
Code analysis:
height = input().split(',') height = [int(x) for x in height]
- These two lines of code take user input and convert the input string into a list of strings using comma delimiters.
- Then, use a list comprehension to convert each element in the list of strings to an integer, and store the result in the
height
list.n = len(height) left, right = 0, n - 1 left_max, right_max = height[0], height[n - 1] summ = 0
- This part of the code initializes the variable
n
, which represents the length of the input listheight
.- In addition, the left pointer (
left
) and the right pointer (right
) are defined and initialized to the first and last elements of the list index of.left_max
andright_max
represent the maximum heights on the left and right sides respectively, which are set to the heights of the first and last elements of the list respectively by default.- Finally, the variable
summ
is used to accumulate the results and is initialized to 0.while left <= right: left_max = max(left_max, height[left]) right_max = max(right_max, height[right]) if left_max < right_max: summ += left_max - height[left] left += 1 else: summ += right_max - height[right] right -= 1
- This part is the main calculation logic, using the double pointer method to traverse the elements in the list.
- When the left pointer is less than or equal to the right pointer, the loop is executed.
- In each loop, by comparing the heights of the corresponding positions of the left and right pointers, the maximum height on the left (
left_max
) and the maximum height on the right (right_max
).- If the maximum height on the left is less than the maximum height on the right, calculate and accumulate the rainwater amount:
left_max - height[left]
, and move the left pointer one position to the right.- Otherwise, calculate and accumulate the amount of rainwater:
right_max - height[right]
, and move the right pointer one position to the left.print(summ)
- Finally, print the accumulated rain volume.