-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrappingRainWater.java
64 lines (55 loc) · 1.78 KB
/
TrappingRainWater.java
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
57
58
59
60
61
62
63
64
public class TrappingRainWater {
public int trap(int[] height) {
int i = 0;
int j = 0;
int result = 0;
while (i < height.length - 1 && j < height.length) {
if (height[i] == 0) {
++i;
j = i;
continue;
}
boolean isIhighest = true;
int temp = i;
int currentHighest = height[temp + 1];
for (int k = temp + 1; k < height.length; k++) {
if (height[k] >= height[i]) {
j = k;
isIhighest = false;
break;
}
if (height[k] >= height[temp] && height[k] > currentHighest) {
j = k;
isIhighest = false;
currentHighest = height[k];
}
temp = k;
}
if (isIhighest) {
i++;
j = i;
continue;
}
int d = j - i - 1;
int minHeight = Math.min(height[i], height[j]);
int area = minHeight * d;
int existingBlocksBetween = 0;
for (int k = i + 1; k < j; k++) {
int extraArea = 0;
if (height[k] > minHeight) {
extraArea = height[k] - minHeight;
}
existingBlocksBetween += height[k] - extraArea;
}
area -= existingBlocksBetween;
result += area;
i = j;
}
return result;
}
public static void main(String[] args) {
TrappingRainWater trappingRainWater = new TrappingRainWater();
int[] height = {4,2,0,3,2,5};
System.out.println(trappingRainWater.trap(height));
}
}