描述
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.
您在真实的面试中是否遇到过这个题?
是
样例
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]
最开始我很笨拙的一个一个加,最后发现,然后就超时了。
然后参考了大佬的微博,http://www.cnblogs.com/grandyang/p/6053827.html
发现思路这么简单。。。
class Solution {
public:
/**
* @param nums: an array
* @return: the minimum number of moves required to make all array elements equal
*/
int minMoves(vector<int> &nums) {
// Write your code here
int mn = INT_MAX, res = 0;
for (int num : nums) mn = min(mn, num);
for (int num : nums) res += num - mn;
return res;
}
};