Minimum Moves to Equal Array Elements

Medium

Topics
ArrayMathGreedy

Given an array nums, in one move you may increment n - 1 elements by 1. Return the minimum number of moves to make all elements equal. Incrementing n-1 elements is equivalent to decrementing one, so the answer is the sum of each element minus the minimum.

Example 1

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

Example 2

101112
Input:  nums = [1,1,1]
Output: 0

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The answer fits in a 32-bit integer
Editorial — intuition, approach, complexity and pitfalls

Intuition

Incrementing n - 1 elements by one is the same as decrementing the remaining one, up to a constant added to every element. Nothing in the question depends on that constant — only on whether the values are equal — so the operation can be reframed as a single decrement with no loss.

Under that reframing the problem is trivial: bring every element down to the minimum, one unit at a time. The count is sum(x - min). Finding the reframing is the whole exercise; the arithmetic that follows is one line.

Approach

  1. Find the minimum.
  2. Sum each element's distance above it.

Dry Run

nums = [1,2,3]        min = 1

  x    x - min   running total
  1    0         0
  2    1         1
  3    2         3

answer 3

check: three real moves on [1,2,3] -- increment two elements each time
  [1,2,3] -> [2,3,3] -> [3,4,3] -> [4,4,4]

Complexity

  • Time — O(n): one pass for the minimum and one for the sum, or both at once.
  • Space — O(1).

Common Pitfalls

  • Simulating the moves. Even inside the constraints the move count is far too large to iterate; the reframing is not an optimisation, it is the only way through.
  • Using the mean or the median as the target. The operation only ever decreases a single element, so the common value reachable with the fewest steps is the minimum, not a central value.
  • Worrying about overflow in the running sum without checking. Every term x - min is non-negative, so the partial sums increase monotonically and the largest is the final answer. The problem guarantees that answer fits in a 32-bit integer, which means no partial sum can overflow either — unlike the other sum-based problems in this set, where the intermediate value is the thing that overflows.
  • Computing sum(nums) - n * min without noticing that sum(nums) alone can be large and negative. It is algebraically identical and fine in 64-bit, but the element-wise form keeps every intermediate value non-negative and bounded by the answer.

Full Solution — all languages

class Solution:
    def minMoves(self, nums):
        mn = min(nums)
        return sum(x - mn for x in nums)
Asked at IBM
SensAI
Beta
Tap the mic to stop voice mode