#K12401. Trapping Rainwater

    ID: 23682 Type: Default 1000ms 256MiB

Trapping Rainwater

Trapping Rainwater

Given a sequence of non-negative integers representing the heights of consecutive buildings, your task is to determine the total amount of rainwater that can be trapped after it rains. The water trapped above the building at index i can be computed using the formula:

\(w_i = \min(L_i, R_i) - h_i\)

where \(L_i\) is the maximum height to the left of index i and \(R_i\) is the maximum height to the right of index i. If this value is negative, consider it as 0.

Your program should read the input from stdin and output the calculated total amount of trapped water to stdout.

inputFormat

The input is given in two lines:

  1. The first line contains an integer n representing the number of buildings.
  2. The second line contains n space-separated non-negative integers representing the heights of the buildings.

outputFormat

Output a single integer denoting the total amount of trapped rainwater.

## sample
5
3 0 2 0 4
7