Problem of the day
You have been given a long type array/list 'arr’ of size 'n’.
It represents an elevation map wherein 'arr[i]’ denotes the elevation of the 'ith' bar.
Print the total amount of rainwater that can be trapped in these elevations.
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:
You don't need to print anything. It has already been taken care of. Just implement the given function.
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.
4
2 1 1 4
2
Water trapped by:
block of height 2 is 0 units.
block of height 1 is 1 unit.
block of height 1 is 3 1 unit.
block of height 4 is 3 0 units.
Hence the total is 2.
5
8 1 8 2 4
9
Water trapped by:
block of height 8 is 0 units.
block of height 1 is 7 units.
block of height 8 is 0 units.
block of height 2 is 2 units.
block of height 4 is 0 units.
Hence the total is 9.
The expected time complexity is O(n).
0 <= n <= 10^6
0 <= arr[i] <= 10^9
Time Limit: 1 sec
Figure a way to calculate the units of water that can be stored at every elevation in the map.
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 :
O(n^2), Where ‘N’ is the total number of elevations in the map.
For every elevation we make ('n' - 1) operations to find the maximum height at the left and right. Hence, the overall space complexity will be O(n^2).
O(1)
We are not using any extra space. Hence, the overall space complexity will be O(1).