Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/ikki-korsatkich-yomgir-suvi

Trapping rain water

Medium 1000 ms 128 MB 51%
Share

$n$ columns of width $1$ stand side by side, the height of the $i$-th column is $h_{i}$. When it rains, water collects in the hollows between the columns (water flows off at both ends). How many units of water are collected in total?

Columns of different heights: the water collected in the hollows between them is highlighted

Input

The first line contains a positive integer $n$.
The second line contains $n$ integers $h_{i}$.

Output

One integer — the amount of collected water.

Note

$1 \le n \le 2 \cdot 10^{5}$
$0 \le h_{i} \le 10^{9}$

Examples

Input #1
12
0 1 0 2 1 0 1 3 2 1 2 1
Output #1
6
Input #2
3
2 0 2
Output #2
2

Sign in to submit a solution

Signing up is free and takes a minute.