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.
1using System;
2
3class Solution {
4 public int MinMoves2(int[] nums) {
5 Array.Sort(nums);
6 int median = nums[nums.Length / 2];
7 int moves = 0;
8 foreach (int num in nums) {
9 moves += Math.Abs(num - median);
10 }
11 return moves;
12 }
13
14 static void Main() {
15 var sol = new Solution();
16 int[] nums = {1, 2, 3};
17 Console.WriteLine(sol.MinMoves2(nums));
18 }
19}
This C# implementation sorts the array using the Array.Sort method and calculates the move count in a straightforward loop.
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.