453. Minimum Moves to Equal Array Elements

来源:互联网 发布:汽车epc软件下载 编辑:程序博客网 时间:2024/06/03 05:15

原题

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]

代码实现

数学等式解决问题

        public int MinMoves(int[] nums)        {             // min+m is the final number            //assume moving m times, so m*(n-1) + sum_init = n * (min+m)             //sum = n*min + m => m = sum - n* min;            int min = nums[0];            int sum = 0;            for (int i = 0; i < nums.Length; i++)            {                if (nums[i] < min) min = nums[i];                sum += nums[i];            }            return sum - nums.Length * min;        }

leetcode-solution库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

原创粉丝点击