Minimum Moves to Equal Array Elements - Math - Easy - LeetCode
💻 coding

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

1 min read 250 words
1 min read
ShareWhatsAppPost on X
  • 1To equalize array elements, the minimum moves required is calculated by the difference between the sum of elements and the product of minimum element and array length.
  • 2Each move increments n - 1 elements by 1, effectively leaving the minimum element unchanged until all elements equalize.
  • 3The solution has a time complexity of O(n) and a space complexity of O(1), making it efficient for large arrays.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To equalize array elements, the minimum moves required is calculated by the difference between the sum of elements and the product of minimum element and array length."

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.

Example:

Input: [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]

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)
 {
 sum+=item;
 min=Math.Min(min,item);
 }
 
 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.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 October 2020 · 1 min read · 250 words

Part of AskGif Blog · coding

You might also like