-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClosestSums.java
66 lines (39 loc) · 1.21 KB
/
ClosestSums.java
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
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class ClosestSums {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int caseNum = 1;
while (in.hasNextInt()) {
int numLines = in.nextInt();
int[] nums = new int[numLines];
for (int i = 0; i < numLines; i++) {
nums[i] = in.nextInt();
}
int numGoals = in.nextInt();
int[] goals = new int[numGoals];
for (int i = 0; i < numGoals; i++) {
goals[i] = in.nextInt();
}
ArrayList<Integer> sums = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
sums.add(nums[i] + nums[j]);
}
}
Collections.sort(sums);
System.out.println("Case " + caseNum + ":");
for (int y : goals) {
int closestNum = sums.get(0);
for (int x : sums) {
if (Math.abs(x - y) < Math.abs(closestNum - y)) {
closestNum = x;
}
}
System.out.println("Closest sum to " + y + " is " + closestNum + ".");
}
caseNum++;
}
}
}