n개의 수가 주어지는데, 이 값들에서 최대 - 최소가 k이하가 되야한다
수가 변경되면 변경된 값의 차이의 절대 값만큼(|a - b|) 비용이 들때
이를 만족하는 경우를 만드는 최소 비용은?
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] lst = new int[n];
for (int i = 0; i < n; i++)
lst[i] = sc.nextInt();
Arrays.sort(lst);
int res = 0;
int diff = (lst[n - 1] - lst[0]) - k;
while (diff > 0){
if (diff % 2 == 0){
lst[0] += diff / 2;
lst[n - 1] -= diff / 2;
res += diff;
}
else{
lst[0] += diff / 2 + 1;
lst[n - 1] -= diff / 2;
res += diff;
}
Arrays.sort(lst);
diff = (lst[n - 1] - lst[0]) - k;
}
System.out.print(res);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] lst = new int[n];
for (int i = 0; i < n; i++)
lst[i] = sc.nextInt();
Arrays.sort(lst);
int min = lst[0];
int max = lst[n - 1];
int res = Integer.MAX_VALUE;
for (int i = min; i <= max; i++){
int tmp = 0;
for (int j = 0; j < n; j++){
if (lst[j] >= i && lst[j] <= i + k)
continue;
tmp += Math.min(Math.abs(lst[j] - i), Math.abs(lst[j] - i - k));
}
res = Math.min(tmp, res);
}
System.out.print(res);
}
}