10/12/2018 - 12:02 PM


Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and plans to give them more than the others. One of the program managers hears of this and tells her to make sure everyone gets the same number.

To make things difficult, she must equalize the number of chocolates in a series of operations. For each operation, she can give chocolates to all but one colleague. Everyone who gets chocolate in a round receives the same number of pieces.

For example, assume the starting distribution is . She can give bars to the first two and the distribution will be . On the next round, she gives the same two bars each, and everyone has the same number: .

Given a starting distribution, calculate the minimum number of operations needed so that every colleague has the same number of chocolates.

Function Description

Complete the equal function in the editor below. It should return an integer that reperesents the minimum number of operations required.

equal has the following parameter(s):

arr: an array of integers to equalize Input Format

The first line contains an integer , the number of test cases.

Each test case has lines.

  • The first line contains an integer , the number of colleagues.
  • The second line contains space-separated integers denoting the number of chocolates each colleague has.


Number of initial chocolates each colleague has <

Output Format

Print the minimum number of operations needed for each test case, one to a line.

Sample Input

1 4 2 2 3 7 Sample Output

2 Explanation

Start with
Add to all but the 3rd element
Add to all but the 4th element

Two operations were required.

#include <bits/stdc++.h>
using namespace std;

int func (int n) {
    int count=0;
    count+= n/5;
    n%= 5;
    count+= n/2;
    n%= 2;
    count+= n;
    return count;
    1. if in each step, a sum of S is added to(n-1) elements and 0 to remaining one element.
    2. This is same as deducting S from one element, 0 from remaining elements. (Work on paper to better understand this step)
    3. The first possibility of these elements being equal is minimum of all the elements. (say min)
    4. No.of steps to make all the array elements equal to min is the minimum no.of steps needed to make all the elements zero.
    5. These elements can also be same if they are equal to min-1/min-2/min-3/min-4. As min-5 takes one extra step from min.
    6. The minimum of number of steps need to be taken to make these elements equal to min/min-1/min-2/min-3/min-4 is the answer.

int main() {
    int t;
    while (t-->0) {
        int n, mi=INT_MAX,ans=INT_MAX;
        vector <int> arr(n);
        for (int i=0;i<n;i++) {
            if (mi>arr[i])
                mi= arr[i];
        for (int i=0;i<5; i++) {
            int temp=0;
            for (int j=0;j<n;j++) {
                temp+= func(arr[j]-mi+i);
            if (temp<ans)
                ans= temp;