//思路:
// 1,數(shù)組排序后
// 2,arr[0]最小绷柒,arr[n-1]最大志于,arr[n-1]與arr[0]相差為x,然后將數(shù)組中最大值以外的數(shù)字全部加上x废睦,此時(shí)arr[0]=arr[n-1],最大值變?yōu)閍rr[n-2]
// 3,重復(fù)第二步操作后,arr[0]=arr[n-1]==arr[n-2],最大值變?yōu)閍rr[n-2]
// 4,重復(fù)n次第二步操作后伺绽,arr數(shù)組中所有數(shù)字相同
// 5.然后將每次的差值x對(duì)應(yīng)的計(jì)算次數(shù)合計(jì)后即為所需計(jì)算次數(shù)
//優(yōu)化:回顧上述步驟后發(fā)現(xiàn),x的值依次為a[n-1]-a[0],a[n-2]-a[0]......an[0]-a[0],因此該問(wèn)題可簡(jiǎn)化為數(shù)組中所有數(shù)字減去最小值后的數(shù)組郊楣,此時(shí)我們發(fā)現(xiàn)排序失去了意義憔恳,只要找到數(shù)組中的最小值即可
//注意:對(duì)于1,5净蚤,5的組合
// 按照上述方法計(jì)算過(guò)程為钥组,加4后獲得5,9今瀑,5程梦,再加4后獲得9点把,9,9屿附,一次加4需要兩次加2實(shí)現(xiàn)郎逃,因此共需4步,
// 但該組合存在更優(yōu)解法挺份,加5后獲得6褒翰,10,5匀泊,再加5后獲得11优训,10,10各聘,再加1后獲得11揣非,11,11躲因,只需3步
static int equal(int[] arr) {
int min = Arrays.stream(arr)
.min().getAsInt();
? ? long sum = Long.MAX_VALUE;
? ? for (int base =0; base <3; base++) {
int finalBase = base;
? ? ? ? int totalTimes = Arrays.stream(arr)
.map(i -> i -min +finalBase)
.map(Solution::getTimes)
.sum();
? ? ? ? sum = Math.min(totalTimes, sum);
? ? }
return (int) sum;
}
//判斷一個(gè)數(shù)字需要5早敬,2,1多少次相加才能獲得
static int getTimes(int diff) {
int times =0;
? ? if (diff >=5) {
times += diff /5;
? ? ? ? diff = diff %5;
? ? }
if (diff >=2) {
times += diff /2;
? ? ? ? diff = diff %2;
? ? }
if (diff >=1) {
times += diff /1;
? ? }
return times;
}