Open In App

Equalize an array using array elements only

Last Updated : 18 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Implementation:

C++




// 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 code
int main()
{
    int arr[] = { 5, 3, 2, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << minOperations(arr, n);
    return 0;
}


Java




// 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




# 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 code
arr = [5, 3, 2, 6 ]
n = len(arr)
print(minOperations(arr, n))
 
# This code is contributed by Smitha Dinesh Semwal


C#




// 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
// 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.
?>


Javascript




<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)

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads