Leetcode 462. Minimum Moves to Equal Array Elements II
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.
You have to determine the minimum moves required to make all elements in the array equal.
import java.util.Arrays;
public class MinimumMoves {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int median = nums[n / 2];
int moves = 0;
for (int num : nums) {
moves += Math.abs(num - median);
}
return moves;
}
public static void main(String[] args) {
MinimumMoves solution = new MinimumMoves();
int[] nums = {1, 2, 3};
System.out.println(solution.minMoves2(nums)); // Output: 2
nums = new int[]{1, 10, 2, 9};
System.out.println(solution.minMoves2(nums)); // Output: 16
}
}
Arrays.sort()
method sorts the array in $O(n \log n)$ time.Thus, the overall time complexity is $O(n \log n)$ due to the sorting step, which is the most computationally expensive operation.
This approach ensures that the solution is both optimal and efficient for large-sized inputs typically encountered in such problems.
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?