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]
正确的解法相当的巧妙,需要换一个角度来看问题,其实给n-1个数字加1,效果等同于给那个未被选中的数字减1,比如数组[1,2,3], 给除去最大值的其他数字加1,变为[2,3,3],我们全体减1,并不影响数字间相对差异,变为[1,2,2],这个结果其实就是原始数组的最大值3自减1,那么问题也可能转化为,将所有数字都减小到最小值
class Solution {
public:
int minMoves(vector<int>& nums) {
int minn=INT_MAX,i,ans=0;
for(i=0;i<nums.size();i++){
minn=min(nums[i],minn);
}
for(i=0;i<nums.size();i++){
ans=ans+nums[i]-minn;
}
return ans;
}
};