[leetcode]: 453. Minimum Moves to Equal Array Elements

来源:互联网 发布:python模块化编程实例 编辑:程序博客网 时间:2024/06/05 06:41

1.题目描述

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,求经过多少次操作可以使数组元素全部相等。

2.分析

数学问题,把公式推出来就好了。设共需要m次操作。数组长度为n,原数组的和为sum,最小元素为min。
最小元素min必然参与每次+1操作(自己写几个列子看看),所有最终数组的每个元素大小为min+m
sum+(n-1)*m=(min+m)*n
故,m=sum-min*n

3.代码

python

def minMoves(nums):    return sum(nums)-min(nums)*len(nums)
0 0