Skip to content

Commit 6a8dd74

Browse files
Create TrappingRainWater
Given an array arr[] with non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season.
1 parent 213fd5a commit 6a8dd74

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class TrappingRainWater {
2+
3+
// arr: input array
4+
// n: size of array
5+
// Function to find the trapped water between the blocks.
6+
static long trappingWater(int arr[]) {
7+
// Your code here
8+
int pmax[]=new int [arr.length];
9+
int smax[]=new int [arr.length];
10+
int max=arr[0];
11+
for(int i=0;i<pmax.length;i++){
12+
pmax[i]=Math.max(max,arr[i]);
13+
max=pmax[i];
14+
}
15+
max=arr[arr.length-1];
16+
// smax[smax.length-1]=arr[arr.length-1];
17+
for(int i=smax.length-1;i>=0;i--){
18+
smax[i]=Math.max(max,arr[i]);
19+
max=smax[i];
20+
}
21+
int lmax=0;
22+
int rmax=0;
23+
long t=0l;
24+
for(int i=0;i<arr.length-1;i++){
25+
lmax=pmax[i];
26+
rmax=smax[i];
27+
if(arr[i]<lmax&&arr[i]<rmax)
28+
t+=Math.min(lmax,rmax)-arr[i];
29+
}
30+
return t;
31+
}
32+
}

0 commit comments

Comments
 (0)