-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrappingRainWater.java
More file actions
39 lines (35 loc) · 880 Bytes
/
TrappingRainWater.java
File metadata and controls
39 lines (35 loc) · 880 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
34
35
36
37
38
39
public class TrappingRainWater {
/**
*
0,1,0,2,1,0,1,3,2,1,2,1
*
* * * *
* * * * * * * * *
0 1 2 3 4 5 6 7 8 9 0 1
l r
time : O(n)
space : O(1)
*
* @param height
* @return
*/
public int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int res = 0;
int leftMax = 0;
int rightMax = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(height[left], leftMax);
res += leftMax - height[left];
left++;
} else {
rightMax = Math.max(height[right], rightMax);
res += rightMax - height[right];
right--;
}
}
return res;
}
}