The "Minimum Moves to Equal Array Elements" problem asks you to determine the minimum number of moves required to make all the elements in an integer array nums
equal. In one move, you can increment n - 1 elements by 1, where n
is the length of the array. The operation can be repeated as many times as needed.
nums
are the same.
Example:
Input: nums = [1,2,3]
Output: 3
At first glance, you might think about incrementing the smallest elements until all match the largest, or performing the operation on random elements until equality is reached. However, simulating each move can quickly become inefficient, especially for large arrays.
A key observation is that incrementing n - 1 elements by 1 is equivalent to decrementing one element by 1 (since the relative difference between elements remains the same). This symmetry means that instead of thinking about increasing all but one, we can think about reducing one element at a time until all elements match the minimum value in the array.
The brute-force approach would be to simulate each move, but with this insight, we can look for a direct formula or shortcut.
Let's break down the optimized solution step by step:
Why does this work? Because each move reduces the gap between the largest and smallest elements by 1, and the total number of gaps to close is the sum of each element's difference from the minimum.
Let's walk through the sample input: nums = [1, 2, 3]
1 - 1 = 0
2 - 1 = 1
3 - 1 = 2
0 + 1 + 2 = 3
Step-by-step moves:
class Solution:
def minMoves(self, nums):
min_num = min(nums)
return sum(num - min_num for num in nums)
class Solution {
public:
int minMoves(vector<int>& nums) {
int min_num = *min_element(nums.begin(), nums.end());
int moves = 0;
for (int num : nums) {
moves += num - min_num;
}
return moves;
}
};
class Solution {
public int minMoves(int[] nums) {
int min = Integer.MAX_VALUE;
for (int num : nums) {
if (num < min) min = num;
}
int moves = 0;
for (int num : nums) {
moves += num - min;
}
return moves;
}
}
var minMoves = function(nums) {
let minNum = Math.min(...nums);
let moves = 0;
for (let num of nums) {
moves += num - minNum;
}
return moves;
};
Brute-force approach:
n - 1
elements, possibly up to the difference between max and min values.The optimized approach is highly efficient and suitable for large arrays.
The key insight in solving the "Minimum Moves to Equal Array Elements" problem is realizing that incrementing n - 1
elements is equivalent to decrementing one element, allowing us to shift our perspective. By summing the differences between each element and the minimum value, we can compute the answer in a single pass. This leads to a clear, concise, and efficient solution with linear time complexity, making it both elegant and practical for large inputs.