453 Minimum Moves to Equal Array Elements

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.




Only three moves are needed (remember each move increments two elements):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

The Idea: To simplify the problem a little bit, think of the equivalent complement. If our goal is to increment all but one until all elements are equal, that is the same as decrementing 1 number until all numbers are the same. The brute force method by the way, is counting the number times you can increment the two smallest numbers until all the elements are the same. In the same way, how many times can we decrement until we reach the minimum? Well this would be all the elements summed up, but the minimum element, and then we would subtract this by the length of the array * the minimum element. The first part counts the number of decrements to zero. The second bit accounts for the fact that we only want to go to the minimum.

Complexity: O(n) time, constant space

def minMoves(self, nums):
    :type nums: List[int]
    :rtype: int

    m = min(nums)
    dec_2_zero = sum(nums) - m
    over_shoot = (len(nums)-1) * m
    return dec_2_zero - over_shoot

Last updated