Rain Caught Between Walls
A row of walls, each one unit wide, stands side by side; their heights are given in the list heights. After a storm, rain is caught in the dips between them: above each place, water rises as high as the walls on both sides can hold it, and anything higher runs off the ends of the row.
Return how many units of rain the row holds.
Examples
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] → 6
heights = [4, 2, 0, 3, 2, 5] → 9
heights = [1, 2, 3] → 0
heights = [3, 0, 3] → 3In the second example the water stands 4 high between the walls of height 4 and 5: 2 + 4 + 1 + 2 = 9 units above the four places in between.
Constraints
- Between 0 and 20,000 walls, each between 0 and 10,000 high.
- Aim for O(n) time and O(1) memory.
Console
›Run to see what your code prints
Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.
Expected is the reference solution's answer, from the judge. An input that breaks the statement's other rules may get any answer.