Trapping Rain Water
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write trap(heights): heights[i] is the height of a bar of width 1 at position i, a whole number 0 or more. After rain, the water over each bar rises to the lower of the tallest bar on its left and the tallest bar on its right, so the bar holds that level minus its own height, if that's more than 0. Return the total water held. An empty array gives 0. For example, trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) is 6. The checks include 100,000 bars, so scanning left and right from every bar is too slow.
Your code must pass
- Adds up the water over every bar
- Holds no water without a taller bar on each side
- Returns 0 for fewer than three bars
- Is fast enough for 100,000 bars