-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRainWater.java
More file actions
27 lines (27 loc) · 827 Bytes
/
Copy pathRainWater.java
File metadata and controls
27 lines (27 loc) · 827 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
class RainWater {
public int trap(int[] height) {
int result = 0;
int left[] = new int[height.length];
int right[] = new int[height.length];
int maxRight = Integer.MIN_VALUE;
int maxLeft = Integer.MIN_VALUE;
// to the right
for (int i = 0; i < height.length; i++) {
if (height[i] > maxRight) {
maxRight = height[i];
}
right[i] = maxRight;
}
// to the left
for (int j = height.length - 1; j >= 0; j--) {
if (height[j] > maxLeft) {
maxLeft = height[j];
}
left[j] = maxLeft;
}
for (int k = 0; k < height.length; k++) {
result += Math.min(left[k], right[k]) - height[k];
}
return result;
}
}