453. Minimum Moves to Equal Array Elements
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]
思路:一个move就是把n-1个元素加一,它的相反面就是将一个元素减一,反正最后到达的效果都是所有元素相等。因此,找到最小的元素,计算所有元素与它的差的和。
class Solution {
public:
int minMoves(vector<int>& nums) {
int n=nums.size();
if(!n) return 0;
int min=nums[0];
for(int i=1;i<n;i++)
if(nums[i]<min) min=nums[i];
int res=0;
for(auto it:nums)
res+=(it-min);
return res;
}
};