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]
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
class Solution {
public:
int minMoves(vector<int>& nums) {
int len = nums.size();
if(len < 2)
return 0;
int min = INT_MAX;
int sum = 0;
for(int i = 0; i < len; ++i)
{
if(min > nums[i])
min = nums[i];
sum += nums[i];
}
return sum - min * len;
}
};
比如1 2 3 5
从最小的数字变为最大的数字 1要经过4步到达5 此时的5就是最小的了 那么接下来 这两个5 5 就做为最小的数字 变为 5 6 7 5 去向最大的数字继续迭代 两步后 变为 7 8 7 7 一步后变为 8 8 8 8 所以说 就是不断的从最小的数字向最大的数字找补的过程,而且找补的过程中,每个数字之间的差值是不会变的。虽然整体上不断增高,但是差值不错。