You are 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.
Q: Is there a constraint on the size of the array?
A: The array size n
can be large, but typically will be up to 50,000 as per common constraints.
Q: What range can the elements of the array nums
take?
A: They can be any integer value, including negative integers.
Q: What does a move exactly entail? A: In one move, you can increase or decrease an element by 1. For example, moving an element value from 5 to 10 would take 5 moves.
The problem is about minimizing the sum of absolute differences to a chosen value. This is a common median problem:
Steps to implement:
Sorting takes (O(n \log n)) and traversing the array takes (O(n)). Thus, the overall time complexity is dominated by the sorting step, making it (O(n \log n)).
def minMoves2(nums):
nums.sort()
median = nums[len(nums) // 2]
return sum(abs(num - median) for num in nums)
# Example Usage
print(minMoves2([1,2,3])) # Output: 2, since we can make 1 and 3 both equal to 2
print(minMoves2([1,10,2,9]))# Output: 16, since we can make 1, 2, and 9 all equal to 10 or vice-versa
In this implementation, we first sort the array to find the median. Then, we calculate the sum of absolute differences to the median. This ensures that we get the minimum number of moves required to make all elements equal.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?