Minimum Moves to Equal Array Elements III Problem
#3736
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3736.
You are given an integer array nums.
In one move, you may increase the value of any single element nums[i] by 1.
Return the minimum total number of moves required so that all elements in nums become equal.
Example 1:
Input: nums = [2,1,3]
Output: 3
Explanation:
To make all elements equal:
- Increase nums[0] = 2 by 1 to make it 3.
- Increase nums[1] = 1 by 1 to make it 2.
- Increase the updated nums[1] = 2 by 1 to make it 3.
Now, all elements of nums are equal to 3. The minimum total moves is 3.
Example 2:
Input: nums = [4,4,5]
Output: 2
Explanation:
To make all elements equal:
- Increase nums[0] = 4 by 1 to make it 5.
- Increase nums[1] = 4 by 1 to make it 5.
Now, all elements of nums are equal to 5. The minimum total moves is 2.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Raise everything to the maximum
A move can only increase an element, so the common final value is at least the maximum. Using exactly the maximum is cheapest, because every element must climb to the target and a higher target only adds moves.
With mx the maximum, s the sum and n the length, the number of moves is mx * n - s.
Complexity: time O(n), space O(1).
class Solution:
def minMoves(self, nums: List[int]) -> int:
n = len(nums)
mx = max(nums)
s = sum(nums)
return mx * n - s