Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped.
intTrapintA[],intN) {intresult =0; //find the highest value/position intMaxhigh =0; intMaxidx =0; for(intI=0; i<n; i++){ if(A[i] >Maxhigh) {Maxhigh=A[i]; Maxidx=i; } } //From the left to the highest postion intPrevhigh =0; for(intI=0; i<maxidx; i++){ if(A[i] >Prevhigh) {Prevhigh=A[i]; } result+ = (Prevhigh-A[i]); } //From the right to the highest postionPrevhigh=0; for(inti=n-1; i>maxidx; i--){ if(A[i] >Prevhigh) {Prevhigh=A[i]; } result+ = (Prevhigh-A[i]); } returnresult;}
* The idea is:
* 1) find the highest bar.
* 2) traverse the bar from left the highest bar.
* becasue we have the ' highest bar in right ' so ' any bar higher than it right bar (s) can contain the water.
* 3) traverse the bar from right the highest bar.
* becasue we have the highest bar in left, so, any bar higher than it left bar (s) can contain the water.
Trapping Rain Water *hard*