PU Minimum Moves to Equal Array Elements

Jan 01, 1970

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:

  • Input: [1,2,3]
  • Output: 3
  • Explanation: Only three moves are needed (remember each move increments two elements):
    • [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

C Solution:

int minMoves(int* nums, int numsSize) {
    int i, sum = nums[0], min = nums[0];
    for (i = 1; i < numsSize; i++) {
        sum += nums[i];
        min = min < nums[i] ? min : nums[i];
    }
    return sum - min * numsSize;
}

Python Solution:

class Solution(object):
    def minMoves(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(nums) - len(nums) * min(nums)

Summary:

  • Explanation:
Given [4, 7, 9, 1].
1   4   7   9   put max 9 in front of the min 1.
9   1   4   7   add 8, which is max - min, to the last three integers. max -min = 9 - 1
9   9   12  15  put max 15 in front of the min 9.
15  9   9   12  add 3, which is max - min, to the last three integers. max - min = 15 - 9 = 7 - 1
15  15  15  18  put max 18 in front of the min 15.
18  15  15  15  add 3, which is max - min, to the last three integers. max - min = 18 - 15 = 12 - 9 = 4 - 1
18  18  18  18  finish.
  • Code is simple, this could be called cliff problem.

LeetCode: 453. Minimum Moves to Equal Array Elements