Minimum Operations To Make Array Equal

Posted: 14 Apr, 2021
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given an array ‘ARR’ of length ‘N’ which is filled with the values such that ARR[i] = (2*i + 1). You have to perform operations on the ‘ARR’ to make all elements of the array equal. In one operation, you can choose two elements from the array ‘ARR’ say ‘i’ and ‘j’, and can increment the value of ‘ARR[i]’ by one and decrement the value of ‘ARR[j]’ by one.

You have to find the minimum number of operations to make all the elements of the array ‘ARR’ equal. It is guaranteed that all elements of the array can be made equal using some operations.

Input format:
The first line of input contains an integer ‘T’, denoting the number of test cases. 

The first line of each test case contains an integer ‘N’, denoting the length of the array.
Output format:
For each test case, print the minimum number of operations to make all the elements of the array equal.

Output for each test case is printed on a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 1000
1 <= N <= 10^9

Time Limit: 1 sec
Follow Up:
Can you do this in constant time and space?
Approach 1
  • The idea behind this approach is we have to calculate the average of all the elements of the array ‘ARR’ because the sum of all elements of the array always remains constant.
  • So calculating the average will help us to virtually divide the elements into two halves around the average i.e left and the right. So calculating the answer for the left half only will be our required answer. It is because in one operation we will choose one element from the left half and one element from the right half and therefore performing operation only left will give us the answer. We will choose the elements which are at equal distance from their average i.e (0 and N-1) or (1 and N-2) etc. therefore if the 0'th element requires ‘K’ operations to become equal to average then the (N-1)'th element will also require ‘K’ operations to become equal to the average and this whole operation to convert 0'th element and the (N-1)'th element will be considered as one single operation.

 

Algorithm:

 

  • Construct an array ARR  of size N such that ARR[i] = (2*i + 1) where 0 <= i < N.
  • Now create a variable Sum initialized to 0 and while constructing the above array add all the elements and store the result in Sum.
  • Now create a variable Avg which denotes the average of all array elements. Set Avg as Sum / N.
  • Create a variable minOperations initialized to 0.
  • Since we have to traverse over only on the left half of the array ARR, So we will traverse over the array ARR till N/2 and for each element find the cost to make it equal to the average i.e (Avg - ARR[i]]) and add this cost to the variable minOperations.
  • Finally, return the minOperations which is our required answer.
Try Problem