# RainWaterProblem

unknown
java
2 months ago
1.8 kB
2
Indexable
Never
```class RainWaterProblem {
public static int findWater(int[] arr) {//arr length take out ArraySize
int arr_size = arr.length;//we created new array of same size
//first array of left max height include itself
int left[] = new int[arr_size];//first array of right max height include itself
int right[] = new int[arr_size];

int water = 0; //Global varable store(OR)Initialize result

left[0] = arr[0];//precompute left array//we are fill left side array
for (int i = 1; i < arr_size; i++)
left[i] = Math.max(left[i - 1], arr[i]);
System.out.println("Left->");
for (int i = 0; i < arr_size; i++)//print left
System.out.print(left[i] + ",");
System.out.println("");

System.out.println("Right->");//print right array
right[arr_size - 1] = arr[arr_size - 1];//precompute right array
for (int i = arr_size - 2; i >= 0; i--)
right[i] = Math.max(right[i + 1], arr[i]);
for (int i = 0; i < arr_size; i++)//print Right
System.out.print(right[i] + ",");
System.out.println("");

System.out.println("Water->");
for (int i = 0; i < arr_size; i++) {
water+= Math.min(left[i], right[i]) - arr[i];//calcu water  with min of left&right build - buildHeight
}
return water;
}
public static void main(String[]args){
System.out.print("Building Height->\n");
int arr[] = new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println(" ");
int ans = findWater(arr);
System.out.println("Total water:"+ ans);
}
}```