Minimum Moves to Equal Array Elements in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of size n, we have to find the minimum number of moves required to make all array elements the same, where a move means incrementing n - 1 elements by 1.

So, if the input is like [3,2,3,4], then the output will be 4.

To solve this, we will follow these steps −

  • n := size of nums

  • if n is same as 0, then −

    • return 0

  • sort the array nums

  • ans := 0

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • ans := ans + nums[i] - nums[0]

  • return ans

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minMoves(vector<int>& nums) {
      int n = nums.size();
      if (n == 0)
         return 0;
      sort(nums.begin(), nums.end());
      int ans = 0;
      for (int i = 0; i < n; i++) {
         ans += nums[i] - nums[0];
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,2,3,4};
   cout << (ob.minMoves(v));
}

Input

{3,2,3,4}

Output

4
raja
Published on 10-Jun-2020 16:20:20
Advertisements