Trapping Rain Water
n bars of width 1 stand side by side on flat ground; bar i has height h_i. It rains heavily,
and water collects in every dip that walls on both sides can hold. Anything not enclosed runs off
past the first and last bars.
More precisely, the water level above bar i is min(L_i, R_i), where L_i is the tallest bar
among bars 1..i and R_i the tallest among bars i..n. Bar i holds min(L_i, R_i) − h_i
units of water.
Print the total amount of water held above all bars.
Input
The first line contains n (1 ≤ n ≤ 10^6).
The second line contains n integers h_1, h_2, …, h_n (0 ≤ h_i ≤ 10^9).
Output
Print one integer: the total units of trapped water. It can exceed 2^31, so use a 64-bit type.
Notes
In the first example the water levels above the bars are 0 1 1 2 2 2 2 3 2 2 2 1. Subtracting the
heights gives 0 0 1 0 1 2 1 0 0 1 0 0, for a total of 6.
In the second example every bar is lower than the one before it, so all the water runs off to the right and nothing is held.