Similar Problems

Similar Problems not available

Minimum Moves To Equal Array Elements - Leetcode Solution

Companies:

LeetCode:  Minimum Moves To Equal Array Elements Leetcode Solution

Difficulty: Medium

Topics: math array  

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 or decrement an element of the array by 1.

Example 1:

Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2]

Example 2:

Input: nums = [1,2,4] Output: 3

Solution:

To make all the elements of the array equal, what we can do is find the minimum and maximum element of the array and then take the difference between them. That difference will be the number of moves required to make all the elements equal.

For example, if we have an array of [1, 2, 4], the minimum element is 1 and the maximum element is 4. The difference between them is 4-1=3, so we need 3 moves to make all the elements of the array equal.

There is one more thing we need to consider, which is the case where the minimum element is negative. In this case, we need to add the absolute value of the minimum element to all the elements in the array. This will make the minimum element zero and all the other elements will be adjusted accordingly. For example, if we have an array of [-1, 2, 4], the minimum element is -1. We add 1 to all the elements and the array becomes [0, 3, 5]. Now the minimum element is zero and the maximum element is 5, so we need 5 moves to make all the elements equal.

Hence, the solution to the problem can be implemented as follows:

Step 1: Initialize variables min_element, max_element, and sum_elements with the first element of the array nums. Step 2: Loop through the remaining elements of nums and update min_element, max_element and sum_elements accordingly. Step 3: If min_element is negative, add the absolute value of min_element to all elements of nums. Step 4: Calculate the difference between max_element and min_element (now zero after addition in step 3) and return it as the answer.

Minimum Moves To Equal Array Elements Solution Code

1