problems / 163

Trapping Rain Water

easy monotonic-stack stack two-pointers arrays 1000 ms · 256 MB

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.

Example 1

Input

12
0 1 0 2 1 0 1 3 2 1 2 1

Output

6

Example 2

Input

5
5 4 3 2 1

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

The water above bar i depends on the tallest bar to its left and the tallest bar to its right, including bar i itself. Why is recomputing those two maxima for every bar too slow for n = 10^6?

Hint 2

Compute the running maximum from the left and from the right in two linear passes, then combine them with each bar's height. Keep the total in a 64-bit integer.

report an issue Prefer your own editor? sooks prep 163 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.