Equalize an array using array elements only

01 Mar, 2022
Given an array of integers, the task is to count minimum number of operations to equalize the array (make all array elements same). And return -1 if it is not possible to equalize. To equalize an array, we need to move values from higher numbers to smaller numbers. Number of operations is equal to number of movements.Examples :  
Input :  arr[] = {1, 3, 2, 0, 4}
Output : 3
We can equalize the array by making value
of all elements equal to 2. To achieve this
we need to do minimum 3 operations (moving
Moving 1 value from arr[1] to arr[0]
Moving 2 values from arr[4] to arr[3]

Input : arr[] = {1, 7, 1}
Output : 4 
 
Method 1 (Simple): First one is brute force approach in which we fix an element and then check for the neighboring elements and then borrow (or give) the required amount of operation. In this approach, we will be needing two loops first one would be used for fixing the elements of the array and the second one would be used to check whether the other neighbors of the present element are able to give them their contribution in equalizing the array. Time complexity of this solution is O(n2);Method 2 (Efficient): 1) Find the sum array elements. If sum % n is not 0, return -1. 2) Compute average or equalized value as eq = sum/n 3) Traverse the array. For every element arr[i] compute absolute value of difference between eq and arr[i]. And keep track of sum of these differences. Let this sum be diff_sum. 4) Return diff_sum / 2.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum operations// needed to equalize an array.#include <bits/stdc++.h>using namespace std; // Returns minimum operations needed to// equalize an array.int minOperations(int arr[], int n){    // Compute sum of array elements    int sum = 0;    for (int i = 0; i < n; i++)        sum += arr[i];     // If average of array is not integer,    // then it is not possible to equalize    if (sum % n != 0)        return -1;     // Compute sum of absolute differences    // between array elements and average    // or equalized value    int diff_sum = 0;    int eq = sum / n;    for (int i = 0; i < n; i++)        diff_sum += abs(arr[i] - eq);     return (diff_sum / 2);} // Driver codeint main(){    int arr[] = { 5, 3, 2, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << minOperations(arr, n);    return 0;}
// Java program to find minimum operations// needed to equalize an array.public class Equalize_Array {         // Returns minimum operations needed to    // equalize an array.    static int minOperations(int arr[], int n)    {        // Compute sum of array elements        int sum = 0;        for (int i = 0; i < n; i++)            sum += arr[i];              // If average of array is not integer,        // then it is not possible to equalize        if (sum % n != 0)            return -1;              // Compute sum of absolute differences        // between array elements and average        // or equalized value        int diff_sum = 0;        int eq = sum / n;        for (int i = 0; i < n; i++)            diff_sum += Math.abs(arr[i] - eq);              return (diff_sum / 2);    }          // Driver code    public static void main(String args[])    {        int arr[] = { 5, 3, 2, 6 };        int n = arr.length;        System.out.println(minOperations(arr, n));    }}// This code is contributed by Sumit Ghosh
# Python3 program to find minimum# operations needed to equalize an array. # Returns minimum operations needed# to equalize an array.def minOperations(arr, n):     # Compute sum of array elements    sum = 0    for i in range(0,n):        sum += arr[i]     # If average of array is not integer,    # then it is not possible to equalize    if sum % n != 0:        return -1     # Compute sum of absolute differences    # between array elements and average    # or equalized value    diff_sum = 0    eq = sum / n    for i in range(0, n):        diff_sum += abs(arr[i] - eq)     return int(diff_sum / 2) # Driver codearr = [5, 3, 2, 6 ]n = len(arr)print(minOperations(arr, n)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find minimum operations// needed to equalize an array.using System; class Equalize_Array {         // Returns minimum operations needed to    // equalize an array.    static int minOperations(int []arr, int n)    {        // Compute sum of array elements        int sum = 0;        for (int i = 0; i < n; i++)            sum += arr[i];             // If average of array is not integer,        // then it is not possible to equalize        if (sum % n != 0)            return -1;             // Compute sum of absolute differences        // between array elements and average        // or equalized value        int diff_sum = 0;        int eq = sum / n;        for (int i = 0; i < n; i++)            diff_sum += Math.Abs(arr[i] - eq);             return (diff_sum / 2);    }         // Driver code    public static void Main()    {        int []arr = {5, 3, 2, 6};        int n = arr.Length;        Console.WriteLine(minOperations(arr, n));    }} // This code is contributed by vt_m.
<?php// PHP program to find minimum// operations needed to// equalize an array. // Returns minimum operations// needed to equalize an array.function minOperations($arr, $n){    // Compute sum of    // array elements    $sum = 0;    for ($i = 0; $i < $n; $i++)        $sum += $arr[$i];     // If average of array is    // not integer, then it is    // not possible to equalize    if ($sum % $n != 0)        return -1;     // Compute sum of absolute    // differences between array    // elements and average or    // equalized value    $diff_sum = 0;    $eq = $sum / $n;    for ($i = 0; $i < $n; $i++)        $diff_sum += abs($arr[$i] -                         $eq);     return ($diff_sum / 2);} // Driver code$arr = array(5, 3, 2, 6);$n = count($arr);echo minOperations($arr, $n); // This code is contributed// by anuj_67.?>
<script>     // JavaScript program to find minimum operations    // needed to equalize an array.         // Returns minimum operations needed to    // equalize an array.    function minOperations(arr, n)    {        // Compute sum of array elements        let sum = 0;        for (let i = 0; i < n; i++)            sum += arr[i];               // If average of array is not integer,        // then it is not possible to equalize        if (sum % n != 0)            return -1;               // Compute sum of absolute differences        // between array elements and average        // or equalized value        let diff_sum = 0;        let eq = parseInt(sum / n, 10);        for (let i = 0; i < n; i++)            diff_sum += Math.abs(arr[i] - eq);               return parseInt(diff_sum / 2, 10);    }         let arr = [5, 3, 2, 6];    let n = arr.length;    document.write(minOperations(arr, n));     </script>
Output:  
3
Time Complexity : O(n)Auxiliary Space : O(1)
This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
divyeshrabadiya07
singhh3010
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
What is Data Structure: Types, Classifications and Applications
Find duplicates in O(n) time and O(1) extra space | Set 1
Next Greater Element
Move all negative numbers to beginning and positive to end with constant extra space
Count pairs with given sum
Find subarray with given sum | Set 1 (Nonnegative Numbers)