Solution: Minimum Moves to Equal Array Elements II

This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode’s forums.

Leetcode Problem #462 (Medium): Minimum Moves to …


This content originally appeared on DEV Community and was authored by seanpgallivan

This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode's forums.

Leetcode Problem #462 (Medium): Minimum Moves to Equal Array Elements II

Description:


(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)

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.

Examples:

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,10,2,9]
Output: 16

Constraints:

  • n == nums.length
  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Idea:


(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)

This problem is deceptive in its simplicity. Ultimately, the value to which you want to set each element equal is the median of the sorted nums array. To come to this realization, we have to first think about the nature of the problem.

Let's consider a possible scenario in which we've decided that our target value is x which would take ans number of moves to complete. What would happen to ans if we increased x by 1? If we did, each element that is below the new x would have to spend another move to get up to x, but every element that is above the new x would have to spend one less move to get down to x.

This means that x should naturally move up if there are more elements above x than below. It also means the inverse, that x should move down if there are more elements below x than above. The natural outcome of this is that x will settle at a spot where there are the same number of elements on either side, which is the median value of nums.

To find the median value, we'll have to first sort nums. If nums has an even number of elements, any value between the two middle elements, inclusive, will work for calculating the answer, so we don't have to worry about which of the two elements we use for our solution.

After we have the median value, we can just iterate through nums and find the sum of the differences of each number from the median value, which should be our answer.

  • Time Complexity: O(N * log N) where N is the length of nums, for sorting nums
  • Space Complexity: O(1)

Javascript Code:


(Jump to: Problem Description || Solution Idea)

var minMoves2 = function(nums) {
    nums.sort((a,b) => a - b)
    let ans = 0, median = nums[~~(nums.length / 2)]
    for (let i = 0; i < nums.length; i++) ans += Math.abs(median - nums[i])
    return ans
}

Python Code:


(Jump to: Problem Description || Solution Idea)

class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        nums.sort()
        ans, median = 0, nums[len(nums) // 2]
        for num in nums: ans += abs(median - num)
        return ans

Java Code:


(Jump to: Problem Description || Solution Idea)

class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int ans = 0, median = nums[~~(nums.length / 2)];
        for (int num : nums) ans += Math.abs(median - num);
        return ans;
    }
}

C++ Code:


(Jump to: Problem Description || Solution Idea)

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int ans = 0, median = nums[~~(nums.size() / 2)];
        for (auto num : nums) ans += abs(median - num);
        return ans;
    }
};


This content originally appeared on DEV Community and was authored by seanpgallivan


Print Share Comment Cite Upload Translate Updates
APA

seanpgallivan | Sciencx (2021-05-19T10:12:19+00:00) Solution: Minimum Moves to Equal Array Elements II. Retrieved from https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/

MLA
" » Solution: Minimum Moves to Equal Array Elements II." seanpgallivan | Sciencx - Wednesday May 19, 2021, https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/
HARVARD
seanpgallivan | Sciencx Wednesday May 19, 2021 » Solution: Minimum Moves to Equal Array Elements II., viewed ,<https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/>
VANCOUVER
seanpgallivan | Sciencx - » Solution: Minimum Moves to Equal Array Elements II. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/
CHICAGO
" » Solution: Minimum Moves to Equal Array Elements II." seanpgallivan | Sciencx - Accessed . https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/
IEEE
" » Solution: Minimum Moves to Equal Array Elements II." seanpgallivan | Sciencx [Online]. Available: https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/. [Accessed: ]
rf:citation
» Solution: Minimum Moves to Equal Array Elements II | seanpgallivan | Sciencx | https://www.scien.cx/2021/05/19/solution-minimum-moves-to-equal-array-elements-ii/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.