Published
- 1 min read
Trapping the rain water
Trapping the rain water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

private void trappingTheRainWater(int height[]) {
int left [] = new int[height.length];
int right [] = new int[left.length];
int len = height.length;
int totalWaterTrapped = 0;
int left = height[0];
for (int i=1 ; i < left.length; i++) {
left[i] = Math.max(left[i-1], height[i]);
}
for(int j= len-2; j < 0; j++) {
right[j] = Math.max(right[j+1], height[j]);
}
for(int x=0; x < height.length; x++) {
totalWaterTrapped += Math.min(left[x], right[x]) - height[x];
}
}