您的位置:首页 > 其它

LeetCode 453. Minimum Moves to Equal Array Elements

2017-07-26 16:44 399 查看

453. Minimum Moves to Equal Array Elements

Description

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]


Solution

题意即给一个n大小的数组,返回最小的更改次数(更改即+1,每次更改n-1个数),使得最终所有的数字相等。

我们先设sum是最后数组的和,m是最小的更改次数,min_num是原始数组中最小的数字,x是最终的数字。

那么我们有
sum + m * (n - 1) = x * n
并且有
x = minNum + m
(贪心的思想) 联立可以解出
sum - minNum * n = m
代码如下

int minMoves(int* nums, int numsSize) {
if (numsSize == 0) return 0;
int min_num = nums[0],sum = nums[0];
for (int i = 1;i < numsSize;i++) {
if (nums[i] < min_num) min_num = nums[i];
sum += nums[i];
}
return sum - numsSize * min_num;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c