We need to calculate the amount of water that has accumulated above each road elevation and sum it up. At a single index/elevation (X), the amount of water depends on the heights of the highest bars to it left and right, regardless of how far apart they are. Upon further exploration, we also observe that the elevation (X) + the height of the water above this elevation, is equivalent to the minimum height of the highest bars around it. Therefore, the accumulation of the water, above a certain point (X), can be calculated using the formula:
Water = minimum ( left_max, right_max ) - value_X
Here, left_max is the highest bar to the left of a certain point (X) and right_max is the highest bar to the right of point (X). If there is no highest bar on either side, the elevation at (X) will be considered the highest bar.
To see this in practice, refer to the diagram below. Here, the left_max (
3
3
units) is smaller than the right_max (
4
4
units). Therefore, the minimum(right_max, left_max) is the left_max (
3
3
units). The elevation at X itself is
2
2
units. Hence, the water above X is
3
−
2
=
1
3−2=1
unit.
X
X
Here is how implementation will take place:
Traverse through the array once.
Calculate the left_max for each point and save it in an array.
Traverse the array again to do the same with right_max.
Traverse the array once more, and use this data to find the amount of water above each point using the formula mentioned above.
Let’s look at the code for the solution: