一、问题描述:
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-1个加一然后计数,但是总是TIME LIMIT
后来换了思路:加和减其实是一样的,每次让最大的减一,减多少次可以得到数组中的最小值。
三、实现代码:
public class Solution {
public int minMoves(int[] nums) {
int sum = 0;
int min = 2147483647;
for (int i = 0; i < nums.length; i++) {
if (nums[i] < min) {
min = nums[i];
}
sum += nums[i];
}
return sum - min * nums.length;
}
}