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]
===================================================================
题目链接:https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
题目大意:给定一个数组,每次给数组中n-1个元素加1,直到所有元素值相等,求最少需要多少步。
思路:给n-1个元素加1,实际上就是给多出来的那个元素减1,所以原来题目可以转化为:每次给数组中的一个元素减1,直到所有元素值相等,求最少需要多少步。
注意点:sum可能超出int范围。
参考代码:
class Solution {
public:
int minMoves(vector<int>& nums) {
long long n = nums.size() ;
if ( n <= 1 )
return 0 ;
long long sum = nums[0] ;
int miner = nums[0] ;
for ( int i = 1 ; i < n ; i ++ )
{
sum += nums[i] ;
miner = min ( miner , nums[i] ) ;
}
return sum - n * miner ;
}
};