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.
Example:
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
Last updated