-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion18.java
More file actions
33 lines (30 loc) · 1.01 KB
/
question18.java
File metadata and controls
33 lines (30 loc) · 1.01 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
public class question18 {
public int trap(int[] height) {
int left = 0, right = height.length - 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) {
question18 solution = new question18();
int[] height = {4, 2, 0, 3, 2, 5};
System.out.println("Trapped Water: " + solution.trap(height));
}
}