Minimum Moves to Equal Array Elements
Problem
In one move you may increment n−1 elements by 1. Return the minimum number of moves to make all elements equal. Equivalently (relative), each move decrements one element by 1 — so the answer is Σ(nums[i] − min).
nums = [1, 2, 3]3def min_moves(nums):
m = min(nums)
return sum(x - m for x in nums)
function minMoves(nums) {
const m = Math.min(...nums);
return nums.reduce((acc, x) => acc + (x - m), 0);
}
class Solution {
public int minMoves(int[] nums) {
int m = Integer.MAX_VALUE;
for (int x : nums) m = Math.min(m, x);
int total = 0;
for (int x : nums) total += x - m;
return total;
}
}
int minMoves(vector<int>& nums) {
int m = *min_element(nums.begin(), nums.end());
int total = 0;
for (int x : nums) total += x - m;
return total;
}
Explanation
The move "increment n-1 elements by 1" sounds tricky, but there is a neat way to flip it: incrementing everyone except one element is, in relative terms, the same as decrementing that one element by 1.
If we think of it as decrements, the goal becomes pulling every element down to the same level. The lowest we can go is the minimum value in the array, since we can only decrease.
So the total number of moves is simply how far each element has to drop to reach the minimum: sum(x - min) over all elements.
The code finds m = min(nums) and adds up x - m for each x. That single sum is the answer.
Example: [1, 2, 3] has min 1. The total is (1-1) + (2-1) + (3-1) = 0 + 1 + 2 = 3.