Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input: [1,2,3] Output: 3 Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
这道题的意思是:每次只对数组中nums.size()-1的元素加1,求经过几步转换能使数组中元素的值都相等。
因为把数组中的数加1最终得到全部相等的值,例如[1,2,3]除3外所有数字加1,变为[2,3,3],这时所有数字减1,变为[1,2,2]数字之间的差值不变,相当于最大值3减1,然后[2,3,3]-->[3,4,3],全部减2得到[1,2,1],相当于最大值3减2,[3,4,3]-->[4,4,4],全部减3得到[1,1,1]所以整个过程可以看作是把2,3逐步减小到1 的过程,所以先求出数组中元素的最小值,然后依次求出每个元素与最小值之间的差值,将差值相加即可。
代码如下:
int mn = Integer.MAX_VALUE, res = 0;
for (int num : nums) mn = Math.min(mn, num);
for (int num : nums) res += num - mn;
return res;