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.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int minMoves2(std::vector<int>& nums) {
6 std::sort(nums.begin(), nums.end());
7 int median = nums[nums.size() / 2];
8 int moves = 0;
9 for (int num : nums) {
10 moves += std::abs(num - median);
11 }
12 return moves;
13}
14
15int main() {
16 std::vector<int> nums = {1, 2, 3};
17 std::cout << minMoves2(nums) << std::endl;
18 return 0;
19}
The C++ solution is similar to the C solution but makes use of the STL sort function to order the array and uses C++ specific constructs like vectors and algorithms.
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.