453. Minimum Moves to Equal Array Elements

LeetCode 力扣

1. Description

Given an integer array nums of length n, make every element equal using as few moves as possible.
Each move selects exactly n - 1 elements and increases each selected element by 1. Return the minimum number of moves.

2. Example

Example 1

Input: nums = [1,2,3]
Output: 3
Explanation: Three moves suffice: [1,2,3] → [2,3,3] → [3,4,3] → [4,4,4]. Each step increases two elements by 1.

Example 2

Input: nums = [1,1,1]
Output: 0
Explanation: All elements already have the same value.

3. Constraints

  • n == nums.length
  • 1 <= nums.length <= 10$^5$
  • -10$^9$ <= nums[i] <= 10$^9$
  • The minimum move count fits in a signed 32-bit integer.

4. Solutions

Math

n = nums.size()
Time complexity: O(n)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    int minMoves(const vector<int> &nums) {
        int min_value = *min_element(nums.begin(), nums.end());
        int count = 0;
        for (int num : nums) {
            count += num - min_value;
        }

        return count;
    }
};
comments powered by Disqus