Last Updated: 31 Jul, 2020

# Trapping Rain Water

Moderate

## Problem statement

#### Print the total amount of rainwater that can be trapped in these elevations.

##### Note :
``````The width of each bar is the same and is equal to 1.
``````
##### Example:
``````Input: ‘n’ = 6, ‘arr’ = [3, 0, 0, 2, 0, 4].

Output: 10

Explanation: Refer to the image for better comprehension:
``````

##### Note :
``````You don't need to print anything. It has already been taken care of. Just implement the given function.
``````
##### Input format :
``````The first line of each test case contains an integer 'n' representing the size of the array/list.

The second line contains 'n' single space-separated integers representing the elevation of the bars.
``````
##### Output Format :
``````Return an integer denoting the amount of water that can be trapped.
``````

## Approaches

### 01 Approach

The idea here is to travel over every elevation on the map and calculate the units of water the elevation can store.

Here is the algorithm :

1. Iterate over every elevation or element and find the maximum elevation on to the left and right of it. Say, the maximum elevation on to the left of the current elevation or element that we are looking at is ‘maxLeftHeight’ and the maximum elevation on to the right of it is ‘maxRightHeight’.
2. Take the minimum of ‘maxLeftHeight’ and ‘maxRightHeight’ and subtract it from the current elevation or element. This will be the units of water that can be stored at this elevation.
3. Compute units of water that every elevation can store and sum them up to return the total units of water that can be stored.