-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBudget.java
More file actions
60 lines (57 loc) · 1.78 KB
/
Copy pathBudget.java
File metadata and controls
60 lines (57 loc) · 1.78 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
import java.util.Arrays;
import java.util.Scanner;
public class Budget {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int target = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
Arrays.sort(nums);
int[] result = new int[2];
int minDiff = Integer.MAX_VALUE;
for (int lo = 0, hi = nums.length - 1; lo < hi; ) {
int sum = nums[lo] + nums[hi];
int diff = Math.abs(target - sum);
if (diff < minDiff) {
minDiff = diff;
result[0] = nums[lo];
result[1] = nums[hi];
}
if (sum < target) {
lo++;
} else if (sum > target) {
hi--;
} else {
break;
}
}
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
// static int[] sum(int[] nums, int target){
// Arrays.sort(nums);
// int[] result = new int[2];
// int minDiff = Integer.MAX_VALUE;
// for (int lo = 0, hi = nums.length - 1; lo < hi; ) {
// int sum = nums[lo] + nums[hi];
// int diff = Math.abs(target - sum);
// if (diff < minDiff) {
// minDiff = diff;
// result[0] = nums[lo];
// result[1] = nums[hi];
// }
// if (sum < target) {
// lo++;
// } else if (sum > target) {
// hi--;
// } else {
// break;
// }
// }
// return result;
// }
}