描述
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;
}
};