Trapping Rain Water
Problem statement
You are given an array height. Each value is the height of one bar, and every bar is one unit wide. The bars stand side by side.
After it rains, water collects between the bars. Return the total units of water that stay on top of the bars.
Water cannot stay past the two ends of the array, because nothing holds it there.
Function
trap(height: int[]) → intExamples
Example 1
height = [3,0,2,0,4]return = 7The tallest bar on the left is 3 and on the right is 4, so the water level between them is 3. The three inner bars hold 3, 1 and 3 units, which adds up to 7.
Example 2
height = [0,2,0,1,0,3]return = 5The bar of height 2 and the bar of height 3 hold water at level 2. The three bars between them have heights 0, 1 and 0, so they hold 2, 1 and 2 units, which adds up to 5.
Example 3
height = [5,4,3]return = 0The heights only go down from left to right, so no bar has a taller bar on its right. Nothing stays, and the answer is 0.
Constraints
1 <= height.length <= 200000 <= height[i] <= 10^5