LeetCode 453. Minimum Moves to Equal Array Elements C#

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 453. Minimum Moves to Equal Array Elements C#相关的知识,希望对你有一定的参考价值。

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:

incrementing n-1 elements by one, means every time need to increment 1 to every number except the maximum. but it‘s hard to implement.

Increment to every nums except max, is as same as decrement 1 on one number until every number equals min number.

 

 1 public class Solution {
 2     public int MinMoves(int[] nums) { 
 3         if(nums.Length==0)
 4         {
 5             return 0;
 6         }
 7         int n = nums.Length;
 8         //Find min value in nums;
 9         int min =nums[0];
10         foreach(int num in nums)
11         {
12             min = Math.Min(min, num);
13         }
14         
15         //calculate the difference of every num from nums and min; ths sum should be the min Moves
16         //add 1 to n-1 is same as minus 1 from the max each time.
17         int moves = 0;
18         foreach(int num in nums)
19         {
20             moves +=(num-min);
21         }
22         return  moves;
23     }
24 }

 



以上是关于LeetCode 453. Minimum Moves to Equal Array Elements C#的主要内容,如果未能解决你的问题,请参考以下文章

453. Minimum Moves to Equal Array Elements(LeetCode)

[leetcode-453-Minimum Moves to Equal Array Elements]

LeetCode 453. Minimum Moves to Equal Array Elements

[LeetCode&Python] Problem 453. Minimum Moves to Equal Array Elements

LeetCode 453. Minimum Moves to Equal Array Elements C#

(Java) LeetCode 453. Minimum Moves to Equal Array Elements —— 最小移动次数使数组元素相等