#K11836. Trapping Rainwater

    ID: 23557 Type: Default 1000ms 256MiB

Trapping Rainwater

Trapping Rainwater

Given a series of non-negative integers representing the heights of buildings, your task is to compute how much rainwater can be trapped between these buildings after a heavy rain.

The water trapped above a building is determined by the formula

\( \text{water}_i = \max(0, \min(L_i, R_i) - H_i) \)

where \(H_i\) is the height of the current building, \(L_i\) is the maximum height to the left of it, and \(R_i\) is the maximum height to the right. The answer is the sum of water trapped above each building.

You will read the building heights from the standard input and output the total trapped rainwater to the standard output.

inputFormat

The input consists of two lines:

  • The first line contains a single integer \(n\) which represents the number of buildings. \(n\) can be zero.
  • The second line contains \(n\) space-separated non-negative integers that represent the heights of the buildings.

If \(n = 0\), the second line will be empty.

outputFormat

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

## sample
5
3 0 2 0 4
7

</p>