Trapping Rainwater Problem Solved - interview question

Check out the easiest solution of trapping rainwater problem that is asked in placement interviews

Problem Statement

The element of array {4,2,0,6,3,2,5} refers the height of block, if it rains then how much water can be trapped between the blocks if the width of each block is 1

Program

public class rainwater{

public static int trappingRainwater(int arr[]){
int trappedWater = 0;
for(int i = 1; i < arr.length-1; i++){
int leftMax = -1;
int rightMax = -1;

for(int k = i+1; k < arr.length; k++){
if(rightMax < arr[k]){
rightMax = arr[k];
}
}

for(int p = i-1; p >= 0; p--){
if(leftMax < arr[p]){
leftMax = arr[p];
}
}

if(leftMax < arr[i] || rightMax < arr[i]){
continue;
}

if(leftMax < rightMax){
trappedWater += leftMax - arr[i];
} else {
trappedWater += rightMax - arr[i];
}
}
return trappedWater;
}


public static void main(String args[]){
int blockHeight[] = {4,2,0,6,3,2,5};
System.out.println(trappingRainwater(blockHeight));
}
}

Sachin Verma
A programming tutor, book writer, poet and a engineering student.