File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ ```
2+ import java.io.*;
3+ import java.util.*;
4+
5+ public class Main {
6+ private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+ private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+ private static int[] arr;
9+ private static int N, K;
10+
11+ public static void main(String[] args) throws IOException {
12+ int T = Integer.parseInt(br.readLine());
13+
14+ while (T-->0) {
15+ init();
16+ int answer = binarySearch();
17+ bw.write(answer + "\n");
18+ }
19+ bw.flush();
20+ bw.close();
21+ br.close();
22+ }
23+
24+ private static void init() throws IOException {
25+ StringTokenizer st = new StringTokenizer(br.readLine());
26+ N = Integer.parseInt(st.nextToken());
27+ K = Integer.parseInt(st.nextToken());
28+
29+ arr = new int[N];
30+ st = new StringTokenizer(br.readLine());
31+ for (int i = 0; i < N; i++) {
32+ arr[i] = Integer.parseInt(st.nextToken());
33+ }
34+
35+ Arrays.sort(arr);
36+ }
37+
38+ private static int binarySearch() {
39+ int left = 0;
40+ int right = N-1;
41+
42+ int minGap = (int)1e8 + 1;
43+ int count = 0;
44+
45+ while (left < right) {
46+ int sum = arr[left] + arr[right];
47+ int gap = Math.abs(sum - K);
48+
49+ if (gap < minGap) {
50+ minGap = gap;
51+ count = 1;
52+ } else if (gap == minGap) {
53+ count++;
54+ }
55+
56+ if (sum < K) {
57+ left++;
58+ } else {
59+ right--;
60+ }
61+ }
62+
63+ return count;
64+ }
65+ }
66+ ```
You can’t perform that action at this time.
0 commit comments