




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)
1#include <stdio.h>
2#include <limits.h>
3
4int minMoves(int* nums, int numsSize) {
5    int min = INT_MAX;
6    int moves = 0;
7    for (int i = 0; i < numsSize; i++) {
8        if (nums[i] < min) {
9            min = nums[i];
10        }
11    }
12    for (int i = 0; i < numsSize; i++) {
13        moves += nums[i] - min;
14    }
15    return moves;
16}
17
18int main() {
19    int nums[] = {1, 2, 3};
20    printf("%d\n", minMoves(nums, 3));
21    return 0;
22}This C solution keeps track of the minimum element and computes the sum of differences between each element and the minimum. This sum is the number of moves needed.