gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Give simple, common, and optimised Java solution public int minMoves (int [] nums) {
- User
Give simple, common, and optimised Java solution
public int minMoves (int [] nums) {
- Assistant
To solve the problem of finding the minimum moves required to make all elements in an array equal (where each move increments or decrements an element by 1), we need to choose an optimal strategy. The most efficient way to achieve this involves finding the median of the array, because the minimum number of moves to make all elements equal occurs when all elements are made equal to the median. Here's a simple, common, and optimized Java solution:
import java.util.Arrays; public class Solution { public int minMoves(int[] nums) { // Sort the array to find the median Arrays.sort(nums); // Calculate the median element int median = nums[nums.length / 2]; // Calculate the total moves required int moves = 0; for (int num : nums) { moves += Math.abs(num - median); } return moves; } }