-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay7.java
More file actions
51 lines (41 loc) · 1.43 KB
/
Day7.java
File metadata and controls
51 lines (41 loc) · 1.43 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
public class TrappingRainWater {
public static int trap(int[] height) {
int n = height.length;
if (n < 3) return 0;
int left = 0, right = n - 1;
int leftMax = 0, rightMax = 0;
int trappedWater = 0;
while (left < right) {
if (height[left] <= height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
trappedWater += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
trappedWater += rightMax - height[right];
}
right--;
}
}
return trappedWater;
}
public static void main(String[] args) {
int[] h1 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
System.out.println("Output: " + trap(h1)); // 6
int[] h2 = {4, 2, 0, 3, 2, 5};
System.out.println("Output: " + trap(h2)); // 9
int[] h3 = {1, 1, 1};
System.out.println("Output: " + trap(h3)); // 0
int[] h4 = {5};
System.out.println("Output: " + trap(h4)); // 0
int[] h5 = {2, 0, 2};
System.out.println("Output: " + trap(h5)); // 2
int[] h6 = {0, 0, 0, 0};
System.out.println("Output: " + trap(h6)); // 0
}
}