Equalize an array using array elements only in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n elements. Our task is to create a program to count the number of operations to equalize an array using elements only.

We need to count the number of adding or subtraction operations that will be performed to make all the elements of the array equal.

Let’s take an example to understand the problem,

Input: arr[] = {4, 0, 3, 1, 2}

Output: 3

Explanation: 

The equal value will be 2.

The overall sum will be the same. We will be taking 1 from value at arr[3] and then adding it to value at arr[1].

Then we will take 2 from value at arr[0] and add it to value at arr[1].

Solution Approach:

A simple solution to the problem is by finding the element from the array to be treated as the elements which will be the equal element for the array.

We will check if the operation is possible by finding the average, if it is integer then equalisation is possible otherwise not.

If equalisation is possible, we will find the count the number of operations that are required and then return it. The count of operation is equal to half of the sum of absolute difference of all numbers with the average.

Algorithm :

Step 1: find the average of all elements of the array.

Step 2: if average is not an integer, return -1, indicating equalisation is not possible.

Step 3: else, find the absolute difference between all elements and the average.

Step 4: Return half of the average value.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int calcEqualisedOperations(int arr[], int n) {
   
   int sum = 0, average, operations = 0;
   for (int i = 0; i < n; i++)
      sum += arr[i];
   if (sum % n != 0)
      return -1;
   average = sum/n;
   for (int i = 0; i < n; i++)
      operations += ( abs(arr[i] - average) / 2 );

   return operations;
}

int main() {

   int arr[] = { 5, 3, 2, 6 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"Operations required to equalize an array using array elements is "<<calcEqualisedOperations(arr, n);
   return 0;
}

Output −

Operations required to equalize an array using array elements is 2
raja
Published on 22-Jan-2021 12:54:47
Advertisements