Water held between the bars
HardStuck?
Show a hintHide the hint
Water above a bar is the smaller of the tallest wall on each side, minus the bar. Walk two pointers inwards and always move the shorter side, because that is the side whose answer is already decided.
The ideas behind this problem
Last problem in this lesson
Go to the next lessonA row of bars stands side by side, each one unit wide, with the heights given. After heavy rain, water settles in the dips. Report how many units of water are held.
Worked example#
For [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]:
#
#~~~##~#
#~##~######
The ~ marks are water. Adding them up gives 6.
The idea#
Look at one bar at a time and ask how deep the water is above it. Water above a bar is held in by the tallest bar somewhere to its left and the tallest somewhere to its right. The shorter of those two walls decides the level, and the water above this bar is that level minus the bar's own height:
water[i] = min(tallest to the left, tallest to the right) - height[i]
Never negative, because one of the two walls is the bar itself in the worst case.
Computing both maxima for every bar separately costs two extra arrays. There is a neater way with two pointers walking inwards. At each step, look at whichever end is shorter. That side's answer is already decided: the other end is taller, so there is guaranteed to be a wall at least that high on the far side, and the near maximum is the one that limits the water. So you can settle that bar and step inwards, keeping only two running maxima.
Constraints#
1 <= n <= 1000000 <= height[i] <= 100000
Input
height is a count then that many integers.
Output
Print the total units of water.
Examples
Input
12 0 1 0 2 1 0 1 3 2 1 2 1
Output
6
Six units settle in the dips between the taller bars.
Input
6 4 2 0 3 2 5
Output
9
The deep gap in the middle is held in by the 4 and the 5.
Input
4 3 2 1 0
Output
0
Heights only fall, so nothing is held in.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.