Problem · Array
Trapping Rain Water
Learn this problemProblem statement
You are given an array heights, where heights[i] is the height of the ith bar in an elevation map. Every bar has width 1.
Return the total amount of rainwater that can be trapped between the bars.
Function
trapRainWater(heights: long[]) → longExamples
Example 1
heights = [3,0,0,2,0,4]return = 10The bars trap 3 + 3 + 1 + 3 = 10 units of water at indices 1, 2, 3, and 4.
Example 2
heights = [8,1,8,2,4]return = 9The first basin traps 7 units above the bar of height 1, and the last basin traps 2 units above the bar of height 2.
Constraints
0 <= heights.length <= 10^60 <= heights[i] <= 10^9- The answer fits in a signed
long.