Tuesday, 19 Oct 2021

# Distributed C candies among N boys such that difference between maximum and minimum candies received is K

Distributed C candies among N boys such that difference between maximum and minimum candies received is KGiven two integers N and C, representing the number of boys and candies, and an integer K, the task is to calculate the maximum and the minimum number of candies received by any boy such that the difference between them is K.Examples:Input: N = 4, C = 12, K = 3Output:Maximum = 5Minimum = 2Explanation:Distribute the {2, 2, 3, 5} candies among N (= 4) boys.Therefore, the difference between the maximum and minimum is 5 – 2 = 3 (= K).Input: N = 2, C = 8, K = 2Output:Maximum = 5Minimum = 3.Approach: The given problem can be solved based on the following observations:If K >= C : All the C candies can be distributed to 1st boy. Therefore, the maximum count of candies will be C and the minimum will be 0.Otherwise, distribute the candies to boys maintaining the maximum and minimum counts to ≤ K.Illustration: Refer to the table below to observe the distribution pattern of candies.Boy ABoy BBoy CDifference K00KK11K-1K+111KK+122K-1K+222K Initially, distribute K candies to the 1st boy.Now, distribute remaining C – K candies to each boy line-wise starting form 2nd boy to Nth boy and then, again from 1st to Nth and so on.                                                                                              Follow the steps below to solve the problem:Initialize two variables, say maximum and minimum, to store the count of maximum and the minimum number of candies a boy can possess.If N = 1: Set maximum = C and minimum = CIf K >= C: Set maximum = C and minimum = 0Otherwise, if K < C, set maximum = K and  minimum = 0. Now, follow the steps below:Initialize a variable, say remain_candy, and set it to C – K.Add (remain_candy / N ) to maximum and minimum.If (remain_candy % N == N-1), increment minimum.Print minimum and maximum value.Below is the implementation of the above approach:C++#include using namespace std;  int max_min(int N, int C, int K){    int maximum, minimum;      if (N == 1) {                          maximum = minimum = C;    }      else if (K >= C) {                          maximum = C;        minimum = 0;    }      else {                          maximum = K;        minimum = 0;                  int remain_candy = C – K;          maximum += remain_candy / N;        minimum = remain_candy / N;                          if (remain_candy % N == N – 1) {                          minimum++;        }    }      cout