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
The allocated array is {4, 4, 4 , 4}Solution
Example
#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!