Skip to content

Commit a8139f9

Browse files
authored
Implement trapped water calculation algorithm
1 parent 48ba1ae commit a8139f9

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
public class trappedWater{
2+
public static int trappedWater(int height[]){
3+
int n = height.length;
4+
5+
//calculate left max boundary - array
6+
int leftMax[] = new int[n];
7+
leftMax[0] = height[0];
8+
for (int i = 1; i < n; i++) {
9+
leftMax[i] = Math.max(height[i], leftMax[i-1]);
10+
}
11+
12+
//calculate right max boundary - array
13+
int rightMax[] = new int[n];
14+
rightMax[n-1] = height[n-1];
15+
for (int i = n-2; i >= 0; i--) {
16+
rightMax[i] = Math.max(height[i], rightMax[i+1]);
17+
}
18+
19+
int trappedWater = 0;
20+
//loop ->
21+
for (int i = 0; i < n; i++) {
22+
//water level = min(leftMaxBoundary , rightMaxBoundary)
23+
int waterlevel = Math.min(leftMax[i], rightMax[i]);
24+
//trappedWater = waterlevel - height[i]
25+
trappedWater = trappedWater + waterlevel - height[i];
26+
}
27+
return trappedWater;
28+
}
29+
public static void main(String[] args) {
30+
int height[] = {4,2,0,6,3,2,5};
31+
System.out.println(trappedWater(height));
32+
}
33+
}

0 commit comments

Comments
 (0)