Problem:
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]
Summary:
For an array of integers of length n, each step adds 1 to the n-1 element, which requires a minimum number of steps to make the numbers in the array all the same.
Analysis:
Shut up array to meet the requirements of the problem as soon as possible, you need to remove the maximum value of the remaining number plus 1, but this method is too inefficient, you can change a way of thinking. Each time the n-1 number in the array is added 1, it is equivalent to minus 1 of the remaining number. So just find the minimum m in the array and calculate the accumulation of the difference between M and the other numbers in the array.
1 classSolution {2 Public:3 intMinmoves (vector<int>&nums) {4 sort (Nums.begin (), Nums.end ());5 intLen = Nums.size (), res =0;6 7 for(inti =1; i < Len; i++) {8Res + = Nums[i]-nums[0];9 }Ten One returnRes; A } -};
Leetcode 453 Minimum Moves to Equal Array Elements