Trapping rain water
import java.util.*;
class tapping{
public static void main(String[] args) {
int height[]={4,6,7,8,9,10,11};
int leftmaxbound[]=new int[height.length];
leftmaxbound[0]=height[0];
// loop for leftmaxbound
for(int i=1;i<height.length;i++){
if(leftmaxbound[i-1]>height[i]){
leftmaxbound[i]=leftmaxbound[i-1];
}
else{
leftmaxbound[i]=height[i];
}
}
//loop for right max bound
int rightmaxbound[]=new int[height.length];
rightmaxbound[height.length-1]=height[height.length-1];
for(int i=height.length-2;i>=0;i--){
//{4,2,0,6,3,2,5};
if(rightmaxbound[i+1]>height[i]){
rightmaxbound[i]=rightmaxbound[i+1];
}
else{
rightmaxbound[i]=height[i];
}
}
int areasum=0;
for(int i=0;i<height.length;i++){
int minwaterlevel=Math.min(leftmaxbound[i],rightmaxbound[i]);
int trapwater=minwaterlevel-height[i];
areasum = areasum + trapwater;
}
System.out.print("The Volume Of Trap water is "+areasum);
}
}
Comments
Post a Comment