3736. Minimum Moves to Equal Array Elements III

LeetCode 力扣

1. Description

Given an integer array nums, determine the fewest moves needed to make all its values equal.
Each move increases exactly one selected element by 1.

2. Example

Example 1

Input: nums = [2,1,3]
Output: 3
Explanation: Increase 2 once and 1 twice to obtain [3,3,3], using three moves in total.

Example 2

Input: nums = [4,4,5]
Output: 2
Explanation: Increasing each 4 once produces [5,5,5] in two moves.

3. Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

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
13
class Solution {
public:
    int minMoves(const vector<int> &nums) {
        int max_value = *max_element(nums.begin(), nums.end());

        int count = 0;
        for (int num : nums) {
            count += max_value - num;
        }

        return count;
    }
};
comments powered by Disqus