-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiamondCollecting.java
More file actions
63 lines (61 loc) · 2.18 KB
/
Copy pathDiamondCollecting.java
File metadata and controls
63 lines (61 loc) · 2.18 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
import java.io.*;
import java.util.*;
public class DiamondCollecting {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("diamond.in"));
PrintWriter pw =
new PrintWriter(new BufferedWriter(new FileWriter("diamond.out")));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[] list = new int[n];
for (int i = 0; i < n; i++) { list[i] = Integer.parseInt(br.readLine()); }
Arrays.sort(list);
// leftmostIndex[i] stores the index of the smallest diamond that can be
// included given that the largest diamond in the case has size list[i].
int[] leftmostIndex = getLeftmost(list, k);
// leftSize[i] stores the maximum number of diamonds given that all
// diamonds have size at most list[i].
int[] leftSize = new int[n];
for (int i = 0; i < n; i++) {
leftSize[i] = i - leftmostIndex[i] + 1;
if (i > 0) { leftSize[i] = Math.max(leftSize[i], leftSize[i - 1]); }
}
// rightmostIndex[i] stores the index of the smallest diamond that can
// be included given that the smallest diamond in the case has size
// list[i].
int[] rightmostIndex = getRightmost(list, k);
// leftSize[i] stores the maximum number of diamonds given that all
// diamonds have size at least list[i].
int[] rightSize = new int[n];
for (int i = n - 1; i >= 0; i--) {
rightSize[i] = rightmostIndex[i] - i + 1;
if (i < n - 1) { rightSize[i] = Math.max(rightSize[i], rightSize[i + 1]); }
}
int ret = 0;
for (int i = 0; i < n - 1; i++) {
ret = Math.max(ret, leftSize[i] + rightSize[i + 1]);
}
pw.println(ret);
br.close();
pw.close();
}
public static int[] getRightmost(int[] list, int k) {
int[] ret = new int[list.length];
int j = list.length - 1;
for (int i = list.length - 1; i >= 0; i--) {
while (j >= 0 && list[j] - list[i] > k) { j--; }
ret[i] = j;
}
return ret;
}
public static int[] getLeftmost(int[] list, int k) {
int[] ret = new int[list.length];
int j = 0;
for (int i = 0; i < list.length; i++) {
while (j < list.length && list[i] - list[j] > k) { j++; }
ret[i] = j;
}
return ret;
}
}