




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)
1function minMoves(nums) {
2    let min = Math.min(...nums);
3    return nums.reduce((acc, num) => acc + num - min, 0);
4}
5
6console.log(minMoves([1, 2, 3]));This JavaScript solution uses the spread operator and array reduce function to efficiently find the minimum and the sum of differences.