Skip to problem
←

Minimum Moves to Equal Array Elements

Easy 0 attempts

You're given an integer array nums. In a single move, you may pick any n - 1 of its elements (that is, all but one) and increase each of them by 1. Determine the smallest number of such moves needed to make every element in the array equal.

Each move increments exactly n - 1 distinct elements, all by one; the excluded element can change between moves. Return only the number of moves. An already equal array, including a single-element array, needs 0 moves.

Function contract

Implement minMoves(nums). Receive a nonempty integer array; values may be negative.

Output: Return the minimum number of moves needed, not the final common value or a modified array.

Example 1

Input
nums = [1,2,3]
Output
3

Example 2

Input
nums = [1,1,1]
Output
0
Constraints
  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Topics

Compare Differences from the Minimum

Subtracting the same value from every element does not affect whether they are equal. After each allowed move, conceptually subtract one from all elements: the chosen n - 1 elements stay unchanged and the excluded element decreases by one.

In that equivalent process, the highest possible common target is the original minimum. Each value needs value - minimum decrements, so sum those differences. This is an argument about relative values; the actual allowed moves still only increment elements.

javascript
function minMoves(nums) {
  let minimum = nums[0];
  for (const value of nums) minimum = Math.min(minimum, value);
  let moves = 0;
  for (const value of nums) moves += value - minimum;
  return moves;
}

Use a loop instead of spreading the array into Math.min, avoiding JavaScript engine argument-count limits. The maximum result under these bounds is below 2 × 10^14, within the exact integer range of Number.

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript