Blogs Hub

Minimum Moves to Equal Array Elements - Math - Easy - LeetCode - MiniTV

Minimum Moves to Equal Array Elements - Math - Easy - LeetCode - मिनी टीवी

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.




Only three moves are needed (remember each move increments two elements):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

public class Solution {
    public int MinMoves(int[] nums) {
        if(nums.Length < 2){
            return 0;   
        int min=Int32.MaxValue;
        int sum=0;
        foreach(int item in nums)
        return sum-min*nums.Length;

Time Complexity: O(n)

Space Complexity: O(1)


let's define sum as the sum of all the numbers, before any moves; minNum as the min number int the list; n is the length of the list;

After say m moves, we get all the numbers as x, and we will get the following equation

 sum + m * (n - 1) = x * n
and actually,

  x = minNum + m
This part may be a little confusing, but @shijungg explained very well. let me explain a little again. it comes from two observations:

the minimum number will always be minimum until it reaches the final number, because every move, other numbers (besides the max) will be incremented too;
from above, we can get, the minimum number will be incremented in every move. So, if the final number is x, it would be minNum + moves;
and finally, we will get

  sum - minNum * n = m
This is just a math calculation.