C++ Program to find minimum k for candy distribution

Suppose we have an array A with n elements. Amal has n friends, the i-th of his friends has A[i] number of candies. Amal's friends do not like when they have different numbers of candies. So Amal performs the following set of actions exactly once −

  • Amal chooses k (0 ≤ k ≤n) arbitrary friends

  • Amal distributes their A[i1] + A[i2] + ... + A[ik] candies among all n friends. During distribution for each of A[i1] + A[i2] + ... + A[ik] candies he chooses new owner. That can be any of n friends. (Any candy can be given to the person, who has owned that candy before the distribution process).

And, the number k is not fixed in advance and can be arbitrary. We have to find the minimum value of k.

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.



So, if the input of our problem is like A = [4, 5, 2, 5], then the output will be 2.


To solve this, we will follow these steps −

sum := 0
ans := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   sum := sum + A[i]
if sum mod n is not equal to 0, then:
   return -1
   sum := sum / n
   for initialize i := 0, when i < n, update (increase i by 1), do:
      if A[i] > sum, then:
         (increase ans by 1)
      return ans


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int n, sum = 0, ans = 0;
   n = A.size();
   for (int i = 0; i < n; i++)
      sum += A[i];
   if (sum % n != 0)
      return -1;
      sum /= n;
      for (int i = 0; i < n; i++)
         if (A[i] > sum)
      return ans;
int main(){
   vector<int> A = { 4, 5, 2, 5 };
   cout << solve(A) << endl;


{ 4, 5, 2, 5 }



Updated on: 08-Apr-2022


Kickstart Your Career

Get certified by completing the course

Get Started