#K74647. Trapping Rainwater

    ID: 34244 Type: Default 1000ms 256MiB

Trapping Rainwater

Trapping Rainwater

You are given a sequence of non-negative integers representing the heights of buildings. The task is to compute the total amount of rainwater that can be trapped between these buildings after it rains.

For each building at index i, the amount of water that can be trapped above it is determined by the formula:

$w_i = \max(0, \min(L_i, R_i) - h_i)$

where:

  • $h_i$ is the height of the building at index i,
  • $L_i = \max\{ h_0, h_1, \dots, h_i \}$ is the maximum height to the left of the current building (including itself),
  • $R_i = \max\{ h_i, h_{i+1}, \dots, h_{n-1} \}$ is the maximum height to the right of the current building (including itself).

Your program should read the number of buildings and the list of building heights from standard input and output the total trapped water to standard output.

inputFormat

The input is given via standard input (stdin) in the following format:

 n
 h0 h1 h2 ... hn-1

Where:

  • n is a non-negative integer representing the number of buildings.
  • hi are non-negative integers representing the heights of the buildings.

outputFormat

Output a single integer to standard output (stdout) which is the total amount of rainwater that can be trapped between the buildings.

## sample
6
0 1 0 2 1 0
1