453. Minimum Moves to Equal Array Elements
Problem Description
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1 elements of the array by 1.
Example 1:
Input: nums = [1,2,3]
Output: 3
Explanation: Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Example 2:
Input: nums = [1,1,1]
Output: 0
Constraints:
n == nums.length1 <= nums.length <= 10⁵-10⁹ <= nums[i] <= 10⁹- The answer is guaranteed to fit in a 32-bit integer.
Solution
Python Solution
class Solution:
def minMoves(self, nums: List[int]) -> int:
# Find minimum element
min_num = min(nums)
# Sum of differences from minimum
moves = 0
for num in nums:
moves += num - min_num
return moves
Time Complexity: O(n)
Where n is the length of the array.
Space Complexity: O(1)
Only constant extra space is used.
Java Solution
class Solution {
public int minMoves(int[] nums) {
// Find minimum element
int min = nums[0];
for (int num : nums) {
min = Math.min(min, num);
}
// Sum of differences from minimum
long moves = 0;
for (int num : nums) {
moves += num - min;
}
return (int) moves;
}
}
Time Complexity: O(n)
Where n is the length of the array.
Space Complexity: O(1)
Only constant extra space is used.
C++ Solution
class Solution {
public:
int minMoves(vector& nums) {
// Find minimum element
int min_num = *min_element(nums.begin(), nums.end());
// Sum of differences from minimum
long long moves = 0;
for (int num : nums) {
moves += num - min_num;
}
return moves;
}
};
Time Complexity: O(n)
Where n is the length of the array.
Space Complexity: O(1)
Only constant extra space is used.
JavaScript Solution
/**
* @param {number[]} nums
* @return {number}
*/
var minMoves = function(nums) {
// Find minimum element
const min = Math.min(...nums);
// Sum of differences from minimum
let moves = 0;
for (const num of nums) {
moves += num - min;
}
return moves;
};
Time Complexity: O(n)
Where n is the length of the array.
Space Complexity: O(1)
Only constant extra space is used.
C# Solution
public class Solution {
public int MinMoves(int[] nums) {
// Find minimum element
int min = nums.Min();
// Sum of differences from minimum
long moves = 0;
foreach (int num in nums) {
moves += num - min;
}
return (int)moves;
}
}
Time Complexity: O(n)
Where n is the length of the array.
Space Complexity: O(1)
Only constant extra space is used.
Approach Explanation
The solution uses a mathematical insight:
- Key Insights:
- Minimum element
- Difference calculation
- Increment equivalence
- Mathematical proof
- Algorithm Steps:
- Find minimum
- Calculate differences
- Sum differences
- Handle overflow
Implementation Details:
- Array traversal
- Minimum finding
- Difference sum
- Type handling
Optimization Insights:
- Single pass
- No sorting needed
- Constant space
- Overflow prevention
Edge Cases:
- Single element
- All equal
- Large numbers
- Negative numbers