Problem:
给一个数组,有n个数,每一个操作定义为将n-1个数自增1,最终使得数组中所有的数相等,求最少要多少个操作?
Solution:
1. 一个逆向思维的运用,n-1个数自增就相当于1个数自减,使得所有数相等,所有结果就是所有数的和减去(数组的长度*最小值)。
2. 可以把这个问题抽象为一个数学问题(一个leetcode高票题解):
let’s define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list;
After, say m moves, we get all the numbers as x , and we will get the following equation
sum + m * (n - 1) = x * n
and actually,
x = minNum + m
and finally, we will get
sum - minNum * n = m
So, it is clear and easy now.
class Solution {
public:
int minMoves(vector<int>& nums) {
return accumulate(nums.begin(), nums.end(), 0) - nums.size() * *min_element(nums.begin(), nums.end());
}
};