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]
实际上,每次更新需要最小的n-1个值去更新。假设总共更新k次。
那么,最终的情况,所有数的和等于(min+k) * n,min是初始数据的最小值,n是数组的长度;
更新k次,每次更新n-1个值,那么就有 sum+(n-1)*k = (min+k)*n;
化简一下,k=sum-min*n
1 class Solution { 2 public: 3 int minMoves(vector<int>& nums) { 4 int min = INT_MAX, sum = 0; 5 for (auto n : nums) { 6 if (n < min) min = n; 7 sum += n; 8 } 9 return sum - min * nums.size(); 10 } 11 };