-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainWater.java
More file actions
52 lines (49 loc) · 1.44 KB
/
TrappingRainWater.java
File metadata and controls
52 lines (49 loc) · 1.44 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
/*
* https://leetcode.com/problems/trapping-rain-water/
*/
public class TrappingRainWater {
public int trap(int[] height) {
int min = 0, max = height.length - 1, total = 0, level = 0;
while (min < max) {
if (height[min] < height[max]) {
level = Math.max(height[min++], level);
total += Math.max(level - height[min], 0);
} else {
level = Math.max(height[max--], level);
total += Math.max(level - height[max], 0);
}
}
return total;
}
private int trap(int[] height, int depth) {
int i, j;
for (i = 0; i < height.length; i++) {
if (height[i] > depth) {
break;
}
}
for (j = height.length - 1; j >= 0; j--) {
if (height[j] > depth) {
break;
}
}
if (i >= j) {
return 0;
}
return hollow(height, i, j, depth) + trap(height, depth + 1);
}
private int hollow(int[] height, int i, int j, int depth) {
int hollow = 0;
for (int k = i + 1; k < j; k++) {
if (height[k] <= depth) {
hollow++;
}
}
return hollow;
}
public static void main(String[] args) {
System.out.println(new TrappingRainWater().trap(
new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}
)); // 6
}
}