Minimum Moves to Equal Array Elements LeetCode Solution

Last updated on October 5th, 2024 at 09:11 pm

Here, We see Minimum Moves to Equal Array Elements LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Math

Companies

LinkedIn

Level of Question

Medium

Minimum Moves to Equal Array Elements LeetCode Solution

Minimum Moves to Equal Array Elements LeetCode Solution

Problem Statement

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

1. Minimum Moves to Equal Array Elements Leetcode Solution C++

	class Solution {
	public:
		int minMoves(vector<int>& nums) {
			int m=INT_MAX;
			for(int n:nums) m = min(m,n);
			int ans=0;
			for(int n:nums) ans+=n-m;
			return ans;
		}
	};

2. Minimum Moves to Equal Array Elements Leetcode Solution Java

class Solution {
    public int minMoves(int[] nums) {
        if(nums==null||nums.length<=1) return 0;
        long min=(long)nums[0];
        long sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=(long)nums[i];
            min=Math.min(min,nums[i]);
        }
        return (int)(sum-min*nums.length);
    }
}

3. Minimum Moves to Equal Array Elements Solution JavaScript

var minMoves = function(nums) {
    if(nums == null || nums.length<=1) return 0;
    let min = nums[0]
    let sum = 0
    for( i = 0;i< nums.length;i++){
        sum += nums[i]
        min = Math.min(min,nums[i])
    }
    return sum-min*nums.length
};

4. Minimum Moves to Equal Array Elements Solution Python

class Solution(object):
    def minMoves(self, nums):
        return sum(nums) - (len(nums) * min(nums))
Scroll to Top