C++ Program to find array of candy distribution to m friends


Suppose we have two numbers n and m. Amal has n candies and m friends. He wants to make a present with candies to each friend. Amal is planning to present all candies and he wants to do this in the most equal manner. He wants to choose such A[i], where A[i] is the number of candies in the i-th friend's present, the maximum A[i] differs from the least A[i] as little as possible. We have to find the array A.

Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can. This problem we can solve by some basic logics or brute-force approach. Follow the following contents to understand the approach better.

So, if the input of our problem is like n = 15; m = 4, then the output will be [3, 4, 4, 4]

Steps

To solve this, we will follow these steps −

for initialize j := m, when j > 0, update (decrease j by 1), do:
   z := n / j
   n := n - z
   print z

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(int n, int m){
   int z;
   for (int j = m; j > 0; j--){
      z = n / j;
      n = n - z;
      cout << z << ", ";
   }
}
int main(){
   int n = 15;
   int m = 4;
   solve(n, m);
}

Input

15, 4

Output

3, 4, 4, 4,

Updated on: 07-Apr-2022

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements