Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Water collected between towers

Tags:

algorithm

I recently came across an interview question asked by Amazon and I am not able to find an optimized algorithm to solve this question:

You are given an input array whose each element represents the height of a line towers. The width of every tower is 1. It starts raining. How much water is collected between the towers?

Example

Input: [1,5,3,7,2] , Output: 2 units Explanation: 2 units of water collected between towers of height 5 and 7     *    *  *w*  *w*  ***  **** ***** 

Another Example

Input: [5,3,7,2,6,4,5,9,1,2] , Output: 14 units  Explanation= 2 units of water collected between towers of height 5 and 7 +              4 units of water collected between towers of height 7 and 6 +               1 units of water collected between towers of height 6 and 5 +              2 units of water collected between towers of height 6 and 9 +              4 units of water collected between towers of height 7 and 9 +              1 units of water collected between towers of height 9 and 2. 

At first I thought this could be solved by Stock-Span Problem (http://www.geeksforgeeks.org/the-stock-span-problem/) but I was wrong so it would be great if anyone can think of a time-optimized algorithm for this question.

like image 855
Ayush Avatar asked Jun 25 '14 17:06

Ayush


People also ask

What will be the maximum water that can be collected between 2 bars if we remove all the bars between them?

Now you have to pick two bars and remove the bars between them such that when rain falls the water collected between two bars is maximum. Note that the distance between bars remains the same after removing the remaining bars. 2. [3 16 10 5 6 12 20 18] ans: 80 (16*(number of integers between 16 and 18)).

Where is maximum amount of water stored?

About three-quarters of Earth's freshwater is stored in glaciers. Therefore, glacier ice is the second largest reservoir of water on Earth and the largest reservoir of freshwater on Earth!


1 Answers

Once the water's done falling, each position will fill to a level equal to the smaller of the highest tower to the left and the highest tower to the right.

Find, by a rightward scan, the highest tower to the left of each position. Then find, by a leftward scan, the highest tower to the right of each position. Then take the minimum at each position and add them all up.

Something like this ought to work:

int tow[N]; // nonnegative tower heights int hl[N] = {0}, hr[N] = {0}; // highest-left and highest-right for (int i = 0; i < n; i++) hl[i] = max(tow[i], (i!=0)?hl[i-1]:0); for (int i = n-1; i >= 0; i--) hr[i] = max(tow[i],i<(n-1) ? hr[i+1]:0); int ans = 0; for (int i = 0; i < n; i++) ans += min(hl[i], hr[i]) - tow[i]; 
like image 77
tmyklebu Avatar answered Sep 20 '22 04:09

tmyklebu