math and geometry September 3, 2022

Minimum moves to equal array elements II

Time O(nlog(n)) Space O(1) Open original problem

We will first take the median of the array by sorting it and take the middle value, this will be our target. Then we take the difference from each number to the target, add that up and return that as our result.

class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        target = sorted(nums)[len(nums)//2]

        res = 0
        for num in nums:
            res += abs(num - target)
        return res

Time Complexity: O(nlog(n))
Space Complexity: O(1)