Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
68 lines (55 loc) · 1.69 KB

File metadata and controls

68 lines (55 loc) · 1.69 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.