-
Notifications
You must be signed in to change notification settings - Fork 277
/
Trapping_Rainwater_problem
38 lines (33 loc) · 1.05 KB
/
Trapping_Rainwater_problem
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
public class TrappingRainWater {
public static int trap(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int n = height.length;
int left = 0, right = n - 1;
int leftMax = 0, rightMax = 0;
int waterTrapped = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
waterTrapped += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
waterTrapped += rightMax - height[right];
}
right--;
}
}
return waterTrapped;
}
public static void main(String[] args) {
int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
System.out.println("Water trapped: " + trap(height));
}
}