-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainWater.java
More file actions
33 lines (29 loc) · 961 Bytes
/
TrappingRainWater.java
File metadata and controls
33 lines (29 loc) · 961 Bytes
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
package Array;
public class TrappingRainWater {
public static int trap(int[] height) {
int leftMax = 0, rightMax = 0, left = 0, right = height.length - 1, water = 0;
if (height.length == 0) return 0;
while (left < right) {
if (height[left] < height[right]) {
if (leftMax <= height[left]) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (rightMax <= height[right]) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
return water;
}
public static void main(String[] args) {
int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
System.out.println(trap(height));
}
}