Equalize an array using array elements only
Last Updated :
18 Jul, 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):
- Find the sum array elements. If sum % n is not 0, return -1.
- Compute average or equalized value as eq = sum/n
- 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.
- 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>
Time Complexity : O(n)
Auxiliary Space : O(1)
Similar Reads
Deleting Elements in an Array - Array Operations In this post, we will look into deletion operation in an Array, i.e., how to delete an element from an Array, such as:Delete an Element from the Beginning of an ArrayDelete an Element from a Given Position in an ArrayDelete First Occurrence of Given Element from an ArrayRemove All Occurrences of an
4 min read
All elements in an array are Same or not? Given an array, check whether all elements in an array are the same or not. Examples: Input : "Geeks", "for", "Geeks" Output : Not all Elements are Same Input : 1, 1, 1, 1, 1 Output : All Elements are Same Method 1 (Hashing): We create an empty HashSet, insert all elements into it, then we finally s
5 min read
Equalize all Array elements by dividing with another Array element Given an array arr[] of N positive integers (> 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 < i, j < N, i and j are d
6 min read
Minimize steps to make Array elements equal by using giving operations Given an arr[] of length N. Then the task is to find minimum steps to make all the elements of the given array equal. Two types of operations can be performed as given below: Choose a prefix of size K, where arr[K] = max element in that chosen sub-array and convert all elements equal to max. Choose
8 min read
Minimum operation to make all elements equal in array Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element. Examples: Input : arr[] = [1, 2, 3, 4]Output :
11 min read
Equal sum array partition excluding a given element Given an array arr[] and an index in it. Find whether the array arr[] can be partitioned into two disjoint sets such that sum of both the sets is equal and none of the sets includes arr[index] Examples : Input : arr[] = {2, 1, 3, 4}, index = 2 Output : No We need to exclude arr[2] which is 3. Possib
13 min read
Minimizing operations for equalizing Array elements Given an array A[] of length N (N>=2) along with an integer X. You are allowed to select two elements A[i] and A[j], such that the absolute difference between their indices is X. Formally, abs (i - j) = X and then decrement one element and increment the other, the task is to output the minimum nu
8 min read
Make all the elements of equal by using given operation Given an array A[] of length N, the task is to return the minimum number of times the below-given operations are required to perform so that all elements become equal. If it is not possible then return -1. Choose two distinct indices i and j. Such that A[i] > A[j]Let X = Ceil((A[i] - A[j])/2)Subt
8 min read
Minimum Bitwise AND operations to make any two array elements equal Given an array of integers of size 'n' and an integer 'k', We can perform the Bitwise AND operation between any array element and 'k' any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make an
10 min read
Make all Array elements equal by replacing it with adjacent elements Given an array A[] of size N, the task is to find the minimum number of moves required to make array elements equal where you can make adjacent elements equal in one move. Examples: Input: A = {1, 6, 5, 1, 7, 1}, N = 6Output: 3Explanation: Replace 6 with 1, 5 with 1, and then at last replace 7 with
5 min read