Sponsored
Sponsored
To minimize the number of moves, the optimal strategy is to move all numbers to the median of the array. The median minimizes the sum of absolute deviations (L1 norm), which provides the least number of moves required to make all elements equal. By sorting the array and picking the middle element (or the average of two middle elements for an even-sized array), we can find the median efficiently.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) for in-place operations aside from sort implementation.
1def min_moves2(nums):
2 nums.sort()
3 median = nums[len(nums) // 2]
4 moves = sum(abs(num - median) for num in nums)
5 return moves
6
7# Test case
8test = [1, 2, 3]
9print(min_moves2(test))
The Python solution leverages Python's sorted function and a generator expression to calculate moves efficiently.
This approach uses a two-pointer technique on a sorted version of the array to calculate the minimum moves. We initialize two pointers, one at the beginning and the other at the end of the sorted array. By incrementing the left pointer and decrementing the right pointer, we accumulate the number of moves required to make each element pair equal.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1).
1
The JavaScript solution sorts the array and uses two indices to iterate towards the center, calculating expected moves.