[Codetree] 특정 수와 근접한 합
30 Sep 2026
Reading time ~1 minute
해당 문제는 코드트리 특정 수와 근접한 합에서 풀어보실 수 있습니다.
풀이1 구현
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int s = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Please write your code here.
int sum = 0;
for(int i = 0; i < n; i++) {
sum+= arr[i];
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
int num = sum-arr[i]-arr[j]-s;
min = Math.min(min,Math.abs(num));
}
}
System.out.println(min);
}
}
풀이2 구현
import java.util.Scanner;
public class Main {
public static final int INT_MAX = Integer.MAX_VALUE;
public static final int MAX_N = 100;
public static int n, s;
public static int[] arr = new int[MAX_N];
public static int arraySum;
public static int ans = INT_MAX;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 입력
n = sc.nextInt();
s = sc.nextInt();
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
// 배열의 값들의 총합을 미리 구해둡니다.
for(int i = 0; i < n; i++)
arraySum += arr[i];
// 모든 쌍을 다 잡아봅니다.
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++) {
// i번과 j번 수를 제외할 경우 남은 숫자들의 총합은 다음과 같습니다.
int newSum = arraySum - arr[i] - arr[j];
int diff = Math.abs(newSum - s);
ans = Math.min(ans, diff);
}
// 정답을 출력합니다.
System.out.print(ans);
}
}