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)

 



Similar Reads

Equalize all Array elements by dividing with another Array element
Given an array arr[] of N positive integers (&gt; 0). The task is to check if it is possible to make all array elements equal by performing the given operation. Print "Yes" if possible, else print "No". The operation that can be performed is Choose two indices i, j, 1 &lt; i, j &lt; N, i and j are distinct.Replace a[i] with value a[i] divided by a[
6 min read
Minimizing Moves to Equalize Array Elements
Given an array arr[] of N integers, For each move, you can select any m (1 &lt;= m &lt;= n) elements from the array and transfer one integer unit from each selected element to one of its adjacent elements at the same time, the task is to find the minimum number of moves needed to make all the integers in the array equal. If it's not possible to ach
7 min read
Minimum removal of people to equalize the number of coins
Given an array X[] of length N. This denotes that ith person has X[i] coins, the task is to output the minimum number of people needed to remove so that, the remaining person will have an equal number of coins. While removing ith person, the below operations will take place, consider that he has X[i] coins, then: That ith person will be removed fro
7 min read
Minimize cost of operation to equalize tower heights
Given heights of n (n &lt;=10000) towers as an array h[]; we need to bring every tower to same height by either adding or removing blocks in a tower. Every addition or removal operation costs a different value in a different tower. The objective is to minimize this cost. Examples: Input : Tower heights h[] = {1, 2, 3} Costs of operations cost[] = {
11 min read
Find the only positive or only negative number in the given Array
Given an array arr[] of either entirely positive integers or entirely negative integers except for one number. The task is to find that number. Examples: Input: arr[] = {3, 5, 2, 8, -7, 6, 9}Output: -7Explanation: Except -7 all the numbers in arr[] are positive integers. Input: arr[] = {-3, 5, -9}Output: 5 Brute Force Approach: A brute force approa
9 min read
Count subarrays consisting of only 0's and only 1's in a binary array
Given a binary array consisting of only zeroes and ones. The task is to find: The number of subarrays which has only 1 in it.The number of subarrays which has only 0 in it.Examples: Input: arr[] = {0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1} Output: The number of subarrays consisting of 0 only: 7 The number of subarrays consisting of 1 only: 7 Input: arr[]
14 min read
Largest element in the longest Subarray consisting of only Even or only Odd numbers
Given an array arr[] of size N, the task is to find the largest element in the longest subarray consisting only of even numbers or odd numbers. Examples: Input: arr[] = { 2, 4, 6, 9, 10, 11 } Output: 6 Explanation: The longest subarray consisting of only even or odd numbers is { arr[0], arr[1], arr[2] }. Since the largest element of the subarray is
17 min read
Maximize sum of atmost K elements in array by taking only corner elements | Set 2
Given an array arr[] and an integer K, the task is to find and maximize the sum of at most K elements in the Array by taking only corner elements. A corner element is an element from the start of the array or from the end of the array. Examples: Input: N = 8, arr[] = {6, -1, 14, -15, 2, 1, 2, -5}, K = 4 Output: 19 Explanation: Here the optimal choi
12 min read
Count of elements in first Array greater than second Array with each element considered only once
Given two sorted array of size N. The task is to find the maximum number of elements in the first array which are strictly greater than the elements of the second array such that an element can be considered only once. Examples: Input: arr1[] = { 20, 30, 50 }, arr2[] = { 25, 40, 60 } Output: 2 Explanation: Maximum 2 elements 30 (30 &gt; 25) and 50
5 min read
Check if an Array can be Sorted by picking only the corner Array elements
Given an array arr[] consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen. Examples: Input: arr[] = {2, 3, 4, 10, 4, 3, 1} Output: Yes Explanation: The order of picking elements from the array and placing in the sorted
5 min read
Article Tags :
Practice Tags :