Rain Water Held Between Bars
Problem statement
A row of bars stands side by side; bar i has width 1 and height height[i]. Rain falls on the whole row and fills every dip until water would spill over a side. Water spills off both ends of the row.
Return how many units of water stay trapped on top of the bars.
Function
trappedWater(height: int[]) → intExamples
Example 1
height = [4,1,3,0,2,5]return = 10The two outer bars (4 and 5) hold the water at level 4 everywhere between them. Above the bars 1, 3, 0 and 2 that gives 3 + 1 + 4 + 2 = 10 units.
Example 2
height = [1,2,3,4]return = 0The heights only rise, so every bar has nothing taller on its left: no water is held.
Example 3
height = [3,0,3,0,1]return = 4Between the two 3s the water rises to 3 (3 units). The last pit is held only by 3 on the left and 1 on the right, so its level is 1 (1 unit). Total 4.
Constraints
1 <= height.length <= 30000 <= height[i] <= 10^5