forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrap.java
More file actions
68 lines (55 loc) · 1.69 KB
/
Trap.java
File metadata and controls
68 lines (55 loc) · 1.69 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package Algorithms.array;
public class Trap {
public int trap1(int[] A) {
if (A == null) {
return 0;
}
int max = 0;
int len = A.length;
int[] left = new int[len];
int[] right = new int[len];
// count the highest bar from the left to the current.
for (int i = 0; i < len; i++) {
left[i] = i == 0 ? A[i]: Math.max(left[i - 1], A[i]);
}
// count the highest bar from right to current.
for (int i = len - 1; i >= 0; i--) {
right[i] = i == len - 1 ? A[i]: Math.max(right[i + 1], A[i]);
}
// count the largest water which can contain.
for (int i = 0; i < len; i++) {
int height = Math.min(right[i], left[i]);
if (height > A[i]) {
max += height - A[i];
}
}
return max;
}
public int trap(int[] A) {
// 2:37
if (A == null) {
return 0;
}
int len = A.length;
int[] l = new int[len];
int[] r = new int[len];
for (int i = 0; i < len; i++) {
if (i == 0) {
l[i] = A[i];
} else {
l[i] = Math.max(l[i - 1], A[i]);
}
}
int water = 0;
for (int i = len - 1; i >= 0; i--) {
if (i == len - 1) {
r[i] = A[i];
} else {
// but: use Math, not max
r[i] = Math.max(r[i + 1], A[i]);
}
water += Math.min(l[i], r[i]) - A[i];
}
return water;
}
}