Rain trapping solution GFG
package datastrusture;
public class Array1 {
// Efficient method
public static int getWater(int[] arr){
int n = arr.length;
int res = 0;
int[] lMax = new int[n];
int[] rMax = new int[n];
lMax[0] = arr[0];
for(int i = 1; i < n; i++) {
lMax[i] = Math.max(lMax[i - 1], arr[i]);
}
rMax[n - 1] = arr[n - 1];
for(int i = n-2; i >= 0; i--){
rMax[i] = Math.max(arr[i], rMax[i + 1]);
}
for(int i = 1; i < n- 1; i++){
res = res + Math.min(lMax[i], rMax[i]) - arr[i];
}
return res;
}
public static int rainWater(int[] arr){
int n = arr.length;
int max = 0;
for(int i = 1; i < n - 1; i++) {
// Finding left maximum
int lMax = arr[i];
for(int j = 0; j < i; j++) {
lMax = Math.max(lMax,arr[j]);
}
// Finding right maximum
int rMax = arr[i];
for(int j = i + 1; j < n; j++){
rMax = Math.max(rMax,arr[j]);
}
max = max + Math.min(rMax,lMax) - arr[i];
}
return max;
}
public static void main(String[] args) {
int[] array = {5,0,6,2,3};
System.out.println(getWater(array));
}
}
Comments
Post a Comment