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]
從一個長度爲n非空整數數組中,找到可以使得數組中每一個元素的值都相等的最少步數,一步是指選擇對數組中的n-1個元素加一。好比將[1,2,3]這個數組達到均等的最小步數要求爲3步,過程以下:java
假設這個具備n個元素的數組中的最小值爲min,這個數組全部元素的和爲sum,使其達到均等的最小步數爲move,均等的值爲target,則能夠獲得公式sum + (n - 1) * move = target * n
。其中,能夠推導出target = min + move
,即在每一步中都會對初始時最小的元素加一。對兩者進行計算能夠得出sum - move = min * n
。數組
至於爲何target = min + move
,其實理由很簡單。假如並非每一步都會將最小的值加一,則這個值永遠是最小值,它將永遠沒法達到最終的目標值。反過來想,這個題目等價於從目標值開始,每一步都會對某個值-1,直到回到初始數組,則每一次都被執行-1獲得的結果就是這個數組的最小值。ui
代碼以下:code
public int minMoves(int[] nums) { int min = Integer.MAX_VALUE; int sum = 0; for(int num : nums) { min = Math.min(min, num); sum += num; } return sum - min * nums.length; }