




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 <iostream>
2#include <vector>
3#include <algorithm>
4
5int minMoves(std::vector<int>& nums) {
6    int minVal = *std::min_element(nums.begin(), nums.end());
7    int moves = 0;
8    for (int num : nums) {
9        moves += num - minVal;
10    }
11    return moves;
12}
13
14int main() {
15    std::vector<int> nums = {1, 2, 3};
16    std::cout << minMoves(nums) << std::endl;
17    return 0;
18}This C++ solution uses the STL to find the minimum element and then calculates the required moves by summing up the differences.