




Sponsored
Sponsored
The problem can be simplified by observing that incrementing n-1 elements is equivalent to decrementing 1 element. Thus, the number of moves required to make all elements in the array equal is equal to the total number of moves required to make all elements equal to the minimum element present in the array.
To achieve this, calculate the difference between each element and the minimum element, summing these differences yields the required number of moves.
Time Complexity: O(n), Space Complexity: O(1)
1import java.util.*;
2
3public class Main {
4    public static int minMoves(int[] nums) {
5        int min = Arrays.stream(nums).min().getAsInt();
6        int moves = 0;
7        for (int num : nums) {
8            moves += num - min;
9        }
10        return moves;
11    }
12
13    public static void main(String[] args) {
14        int[] nums = {1, 2, 3};
15        System.out.println(minMoves(nums));
16    }
17}This Java solution uses Streams to find the minimum value and accumulate the differences to compute the total moves.