Algorithm
Problem Name: 453. Minimum Moves to Equal Array Elements
Problem Link: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
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.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109
- The answer is guaranteed to fit in a 32-bit integer.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int minMoves(int[] nums) {
Arrays.sort(nums);
int moves = 0;
for (int i = 1; i < nums.length; i++) {
int diff = (moves + nums[i]) - nums[i - 1];
nums[i] += moves;
moves += diff;
}
return moves;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const minMoves = function(nums) {
let min = Number.MAX_SAFE_INTEGER;
let sum = 0;
for (let i = 0; i < nums.length; i++) {
min = Math.min(min, nums[i]);
sum += nums[i];
}
return sum - min * nums.length;
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(nums) - min(nums) * len(nums)
Copy The Code &
Try With Live Editor
Input
#4 Code Example with C# Programming
Code -
C# Programming
using System.Linq;
namespace LeetCode
{
public class _0453_MinimumMovesToEqualArrayElements
{
public int MinMoves(int[] nums)
{
var min = nums.Min();
var count = 0;
foreach (var num in nums)
count += num - min;
return count;
}
}
}
Copy The Code &
Try With Live Editor
Input