Practice · Two pointers · 5 of 5

Rainwater Between Bars

You are given a list height of non-negative integers: the heights of bars of width 1 standing side by side. Rain falls on them and settles in the dips.

Above position i, water rises to the lower of two heights: the tallest bar from the start up to i, and the tallest bar from i to the end. The water above i is that level minus height[i]. Return the total amount of water trapped.

Example 1

Input
height = [3, 0, 2, 0, 4]
Output
7
Between the outer bars the level is 3, so positions 1, 2 and 3 hold 3 + 1 + 3 = 7.

Example 2

Input
height = [0, 2, 0, 1, 0, 3, 1, 0, 2]
Output
8

Example 3

Input
height = [5, 4, 3]
Output
0
The bars only get lower, so every drop runs off the end.

Constraints

  • height holds 1 to 2 × 10⁴ numbers.
  • Every height is between 0 and 10⁵.