Minimum Moves to Equal Array Elements

Given an integer array nums of size n, return the minimum number of moves to make all array elements equal, where a move is incrementing n-1 elements by 1.

Example 1
Input: [1,2,3] → Output: 3
Example 2
Input: [1,1,1] → Output: 0

Solution Approach

Incrementing n-1 elements by 1 is equivalent to decrementing 1 element by 1. So the answer is sum(nums) - n*min(nums).

  • min = min(nums).
  • Answer = sum(nums) - n * min.
Java
class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE, sum = 0;
        for (int n : nums) { sum += n; min = Math.min(min, n); }
        return sum - min * nums.length;
    }
}
  • Time Complexity: O(N)
  • Space Complexity: O(1)