Home >Backend Development >C++ >In C++, find the number of operations required to make all elements of an array equal

In C++, find the number of operations required to make all elements of an array equal

WBOY
WBOYforward
2023-09-03 19:01:10852browse

In C++, find the number of operations required to make all elements of an array equal

In this problem, we get an array arr of size n. Our task is to find the number of operations required to make all array elements equal. ##.

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

Let us take an example to understand this problem,

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

The allocated array is {4, 4, 4 , 4}Solution

A simple way to solve this problem is to find the maximum value of the array. This maximum value is then used to check if all elements of the array are equal and if the value is equal to the maximum value of the array minus n (or a multiple thereof). If yes, n is returned, if no, -1 is returned (indicating that it is 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

The above is the detailed content of In C++, find the number of operations required to make all elements of an array equal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete