- 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]
思路:原本想着一步一步求最大的值,然后对于其他的值加+1,直到最终结果相同。
后来发现可以逆向思维,找到最小的值之后,其他的减1,即找到每个数与最小值的差就可以了。
code:
class Solution {
public:
int minMoves(vector<int>& nums) {
int min = INT_MAX;
for(int i=0;i<nums.size();i++){
if(min>nums[i]){
min = nums[i];
}
}
int sum=0;
for(int i=0;i<nums.size();i++){
sum+=nums[i]-min;
}
return sum;
}
};