The original title link is here: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
Topic:
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]
Exercises
After sort, nums[0] is the minimum value, and nums[nums.length-1] is the maximum value. If you want to increase the minimum value to the maximum you need to do nums[nums.length-1]-nums[0] times move.
Then nums[nums.length-2] becomes the maximum value, nums[0], nums[nums.length-1] equal, are the minimum values. If you want to increase the minimum value to the maximum you need nums[nums.length-2]-nums[0] move.
And so on, the total number of moves equals (num[nums.length-1]-nums[0]) + (Nums[nums.length-2]-nums[0]) + .... + (Nums[1]-nums[0]).
Time Complexity:o (NLOGN). Space:o (1).
AC Java:
1 Public classSolution {2 Public intMinmoves (int[] nums) {3 Arrays.sort (nums);4 intmove = 0;5 for(inti = nums.length-1; i>0; i--){6Move + = (nums[i]-nums[0]);7 }8 returnmove;9 }Ten}
DP, sort and then split the original problem into small problems. When the Nums 0 to i-1 position has been equal, add the new I position, only need to do diff = num[i]-nums[i-1] Move can be all equal.
Of course, the previous 0 to i-1 in the process of nums[i] has been added, the increase is equal to the previous 0 to i-1 the total number of moves.
Nums[i] + = moves into a new nums[i], Nums[i]-nums[i-1] is the number of moves required for this step.
Time Complexity:o (NLOGN). Space:o (1).
AC Java:
1 Public classSolution {2 Public intMinmoves (int[] nums) {3 Arrays.sort (nums);4 intMoves = 0;5 for(inti = 1; i<nums.length; i++){6Nums[i] + =moves;7Moves + = (nums[i]-nums[i-1]);8 }9 returnmoves;Ten } One}
Mathematical method, each time the n-1 element plus one equates to 1 element minus one.
Time Complexity:o (n). Space:o (1).
AC Java:
1 Public classSolution {2 Public intMinmoves (int[] nums) {3 intMin =Integer.max_value;4 for(intnum:nums) {5Min =math.min (min, num);6 }7 8 intMoves = 0;9 for(intnum:nums) {TenMoves + = (num-min); One } A returnmoves; - } -}
Leetcode Minimum Moves to Equal Array Elements