Trapping Rain Water
Tarnbrook Council has a cross-section of a kerbside gutter, measured as a row of blocks. Each number is the height of one block, and every block is exactly one unit wide. After a downpour, water sits in the dips between higher blocks and drains away over the ends of the row, so no water is ever held above the outermost high points. The council wants the volume the gutter holds before it overflows.
Task: Print how many units of water stay in the gutter after rain.
Input
A single line holding up to 100000 integers separated by single spaces — the block heights in order across the gutter. Every value is zero or more. The line can be empty.
Output
One line holding a single integer: the total units of water held. Since each block is one unit wide, the water resting over a block is however far the water level sits above that block's own height. Water is held only where a taller block stands somewhere to the left and another taller block somewhere to the right. Print 0 when nothing is held, including for an empty line.
Example:
Input:
0 1 0 2 1 0 1 3 2 1 2 1
Output:
6
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in