#C5974. Trapped Water Calculation

    ID: 49682 Type: Default 1000ms 256MiB

Trapped Water Calculation

Trapped Water Calculation

You are given an array of non-negative integers where each integer represents the height of a building. Imagine that it rains and water is trapped between the buildings. Your task is to calculate how much water can be trapped in total.

The water trapped at any position i is determined by the formula:

\( \text{water}[i] = \min(\text{left\_max}[i],\, \text{right\_max}[i]) - \text{height}[i] \)

where :

  • \( \text{left\_max}[i] \) is the maximum height of a building to the left of position i (inclusive).
  • \( \text{right\_max}[i] \) is the maximum height of a building to the right of position i (inclusive).

Your solution should read from standard input and write the result to standard output.

inputFormat

The input consists of two lines:

  • The first line contains a single integer n, representing the number of buildings.
  • The second line contains n non-negative integers separated by spaces, representing the heights of the buildings.

If n is 0, then no further input is provided.

outputFormat

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

## sample
12
0 1 0 2 1 0 1 3 2 1 2 1
6

</p>