📅  最后修改于: 2023-12-03 15:12:25.664000             🧑  作者: Mango
在给定数组中,通过添加1、2或5来最小化使所有数组元素相同所需的步骤。本文将介绍一种解决该问题的算法。
public int minSteps(int[] arr) {
int n = arr.length;
int sum = 0;
int average = 0;
for (int i = 0; i < n; i++) {
average += arr[i];
}
average /= n;
int averageInt = Math.round(average);
for (int i = 0; i < n; i++) {
int diff = arr[i] - averageInt;
if (diff != 0) {
int mod = Math.abs(diff) % 5;
sum += Math.abs(diff) / 5;
if (mod == 1 || mod == 4) {
sum += 1;
} else if (mod == 2 || mod == 3) {
sum += 2;
}
}
}
return sum;
}
输入:[1, 2, 3],输出:2。
输入:[5,5,5,5,5],输出:0。
输入:[1,1,1,1,1,1,8,8,8,8,8,8],输出:21。