Description
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
Math, time O(n), space O(1)
这道题乍一看会没什么头绪,竟然还想到用递归去做。但后来发现还是有规律可循。
首先,将n - 1个元素都+1,等同于将数组中的某1个元素-1。
然后,本题最优的解法就是,将所有元素都变成数组的min元素。
所以moves = sum - n * min。
class Solution {
public int minMoves(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int sum = 0;
int min = Integer.MAX_VALUE;
for (int n : nums) {
sum += n;
min = Math.min(n, min);
}
return sum - nums.length * min;
}
}