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.
1function minMoves2(nums) {
2 nums.sort((a, b) => a - b);
3 const median = nums[Math.floor(nums.length / 2)];
4 return nums.reduce((acc, num) => acc + Math.abs(num - median), 0);
5}
6
7console.log(minMoves2([1, 2, 3]));
The JavaScript code sorts the array with the built-in sort method and uses reduce to tally up the total moves.
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).
This Java algorithm sorts the array and uses two pointers to calculate the number of moves needed. The algorithm is efficient and straightforward.