Proficient Level

Implement the method trappedRainWater that calculates how much water can be trapped between bars.

Each value represents a bar height. Water can be held where a lower bar has taller boundaries on both sides.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size elements.
  • Bars with height 0 are allowed.
  • Return the total trapped units.
Example 1
Input:
heights (int[]) = [0,1,0,2,1,0,1,3,2,1,2,1]
size (int) = 12
Return:
(int) 6
Example 2
Input:
heights (int[]) = [4,2,0,3,2,5]
size (int) = 6
Return:
(int) 9
Example 3
Input:
heights (int[]) = [1,2,3]
size (int) = 3
Return:
(int) 0

Move the pointer on the side with the smaller height while tracking the best boundary seen from that side.

Run your code to see the result.