Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements E Qual, where a move is incrementing n -1 elements by 1.
Example:
Input:[1,2,3]output:3explanation:only three moves is needed (remember each move increments both elements): [+] =& gt; [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, are as same as decrement 1 on one number until every number equals min number.
1 Public classSolution {2 Public intMinmoves (int[] nums) { 3 if(Nums. length==0)4 {5 return 0;6 }7 intn =Nums. Length;8 //Find min value in Nums;9 intMin =nums[0];Ten foreach(intNuminchnums) One { AMin =math.min (Min, num); - } - the //Calculate the difference of every num from nums and min; ths sum should being the min Moves - //Add 1 to n-1 are same as minus 1 from the max each time. - intMoves =0; - foreach(intNuminchnums) + { -Moves + = (num-min); + } A returnmoves; at } -}
Leetcode 453. Minimum Moves to Equal Array Elements C #