Skip to content

Commit 2ba228f

Browse files
Add Trapping Rain Water algorithm in Java
1 parent b1aa896 commit 2ba228f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
public class TrappingRainWater {
4+
5+
/**
6+
* Calculates total water trapped between the pillars.
7+
*
8+
* @param height array of non-negative integers representing pillar heights
9+
* @return total units of trapped water
10+
*/
11+
public static int trap(int[] height) {
12+
int n = height.length;
13+
if (n == 0) return 0;
14+
15+
int sum = 0;
16+
int topmax = 0;
17+
int temp2 = 0;
18+
19+
// Find the index of the tallest pillar
20+
for (int i = 0; i < n; i++) {
21+
if (height[i] > temp2) {
22+
topmax = i;
23+
temp2 = height[i];
24+
}
25+
}
26+
27+
int temp = height[0];
28+
29+
for (int i = 0; i < n; i++) {
30+
if (i == 0) {
31+
sum += Math.min(height[i], height[topmax]) - height[i];
32+
} else if (i > 0 && i < topmax) {
33+
if (temp < height[i]) {
34+
temp = height[i];
35+
sum += Math.min(height[i], height[topmax]) - height[i];
36+
} else {
37+
sum += Math.min(temp, height[topmax]) - height[i];
38+
}
39+
} else if (i == topmax) {
40+
// do nothing
41+
} else if (i > topmax) {
42+
int temp1 = height[i];
43+
int j = i;
44+
while (j < n - 1) {
45+
if (temp1 < height[j + 1]) {
46+
temp1 = height[j + 1];
47+
}
48+
j++;
49+
}
50+
sum += Math.min(height[topmax], temp1) - height[i];
51+
}
52+
}
53+
54+
return sum;
55+
}
56+
}

0 commit comments

Comments
 (0)