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个元素+1,求最小移动次数使得元素都相等。给n-1个数字加1,相当于给那个未被选中的数字减1,问题也可以转化为,将所有数字都减小到最小值只要先找到最小值,然后累加每个数跟最小值之间的差值即可。
class Solution {
public:
int minMoves(vector<int>& nums) {
int n = INT_MAX;
int res = 0;
for(int i : nums)
n = min(n , i);
for(int i : nums)
res += i - n;
return res;
}
};
版权声明:本文为weixin_41814716原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。