Find the number of operations required to make all array elements Equal in C++


In this problem, we are given an array arr of size n. Our task is to Find the number of operations required to make all array elements Equal

The operation is defined as distribution of equal weights from the element with maximum weight to all the elements of the array.

If it is not possible to make array elements equal, print -1. 

Let’s take an example to understand the problem, 

Input : arr[] = {7, 3, 3, 3}
Output : 3

Explanation

Array after distribution is {4, 4, 4, 4}

Solution Approach

A simple solution to the problem is by finding the largest value of the array. And then using this largest value check if all elements of the array are equal and the value is equal to the subtraction of n (or its multiples) from the maximum value of the array. If yes, return n, if No, return -1 (denoting not possible).

Example

Let’s take an example to understand the problem

#include<bits/stdc++.h>
using namespace std;
int findOperationCount(int arr[],int n){
   int j = 0, operations = 0;
   int maxVal = arr[0];
   int minVal = arr[0];
   int maxValInd = 0;
   for (int i = 1; i < n; i++){
      if(arr[i] > maxVal){
         maxVal = arr[i];
         maxValInd = i;
      }
      if(arr[i] < minVal){
         minVal = arr[i];
      }
   }
   for (int i =0;i<n;i++){
      if (arr[i] != maxVal && arr[i] <= minVal && arr[i] != 0){
         arr[j] += 1;
         arr[maxValInd] -= 1;
         maxVal -= 1;
         operations += 1;
         j += 1;
      }
      else if (arr[i] != 0){
         j += 1;
      }
   }
   for (int i = 0; i < n; i++){
      if (arr[i] != maxVal){
         operations = -1;
         break;
      }
   }
   return operations;
}
int main(){
   int arr[] = {4, 4, 8, 4};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"The number of operations required to make all array  elements Equal is "<<findOperationCount(arr, n);
   return 0;
}

Output

The number of operations required to make all array elements Equal is 3

Updated on: 24-Jan-2022

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements