forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainWater.java
More file actions
56 lines (49 loc) · 1.6 KB
/
TrappingRainWater.java
File metadata and controls
56 lines (49 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.thealgorithms.dynamicprogramming;
public class TrappingRainWater {
/**
* Calculates total water trapped between the pillars.
*
* @param height array of non-negative integers representing pillar heights
* @return total units of trapped water
*/
public static int trap(int[] height) {
int n = height.length;
if (n == 0) return 0;
int sum = 0;
int topmax = 0;
int temp2 = 0;
// Find the index of the tallest pillar
for (int i = 0; i < n; i++) {
if (height[i] > temp2) {
topmax = i;
temp2 = height[i];
}
}
int temp = height[0];
for (int i = 0; i < n; i++) {
if (i == 0) {
sum += Math.min(height[i], height[topmax]) - height[i];
} else if (i > 0 && i < topmax) {
if (temp < height[i]) {
temp = height[i];
sum += Math.min(height[i], height[topmax]) - height[i];
} else {
sum += Math.min(temp, height[topmax]) - height[i];
}
} else if (i == topmax) {
// do nothing
} else if (i > topmax) {
int temp1 = height[i];
int j = i;
while (j < n - 1) {
if (temp1 < height[j + 1]) {
temp1 = height[j + 1];
}
j++;
}
sum += Math.min(height[topmax], temp1) - height[i];
}
}
return sum;
}
}