Home > Backend Development > C++ > body text

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

WBOY
Release: 2023-09-03 19:01:10
forward
807 people have browsed it

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
Copy after login
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;
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template