public class Solution {
public int minMoves(int[] nums) {
int n = nums.length;
if ( n <= 1 )
return 0;
int sum = 0;
int max = Integer.MIN_VALUE;
for ( int i = 0; i < n; i ++ ){
sum += nums [ i ];
if ( nums [ i ] > max )
max = nums [ i ];
}
int targetedSum = max * n;
while ( (targetedSum - sum) % ( n - 1 ) != 0 ){
targetedSum += n;
}
return ( targetedSum - sum ) / ( n - 1 );
}
}
这个方法不越界的话应该可以 failed [1,1, integer_max]
before all elements reach to the same value, every time (n-1) elements add one meaning only one element remains the same, which of cause should be the max value( should be different from min value, otherwise they have reached the same value) of the array. So, with that being said, every time doing add one for (n-1) operation, the min value +1. If it takes m moves to reach x, then x=minNum+m. Also, I have a similar post, my post, you can take a look if you are still interested.
证明 target - min = step
so
sum - minNum * n = step
public class Solution {
public int minMoves(int[] nums) {
int min = Integer.MAX_VALUE;
int sum = 0;
for ( int i = 0; i < nums.length; i ++ ){
if ( min > nums [ i ] )
min = nums [ i ];
sum += nums [ i ];
}
return sum - min * nums.length;
}
}