Children's day
On children's day, a teacher wants to distribute candies to all her students. She has N
candies, and each candy has a special value. She wants all candies to have the same
special value so she decides to reduce the special values of some candies. However, the
special values of all the candies cannot be reduced.
Hence, she decides to reduce the special values for as much candies as possible so that
at least K candies have the same special value and this value must be as large as
possible. Find the maximum value that the teacher can achieve.
Input Specification:
input1: N, total number of candies
input2: K, candies having the same special value
input3: The array representing the special values of the candies with in
Output Specification:
Return the maximum value that the teacher can achieve.
write a java program for this ?
Answers
Answer:
Input: N = 7, K = 4
Output: 1 2 3 1
At the first turn, the fourth people has to be given 4 candies, but there is
only 1 left, hence he takes one only.
Input: N = 10, K = 3
Output: 5 2 3
Answer:
class GFG {
static void candies(int n, int k){
int[] arr = new int[k];
int j = 0;
while(n>0){
for(int i =0;i<k;i++){
j++;
if(n<=0){
break;
}
else{
if(j<n){
arr[i] = arr[i]+j;
}
else{
arr[i] = arr[i]+n;
}
n = n-j;
}
}
}
for(int i:arr){
System.out.print(i+" ");
}
}
public static void main(String[] args)
{
int n = 10, k = 3;
candies(n, k);
}
}
Explanation:
- A naïve technique is to repeat for each round and distribute candies as needed until all of the candies have been distributed.
- Zero is the time complexity (Number of distributions)
- A better way is to calculate the total of natural numbers until the final phrase of the series, which is (turns*k), and then remove the sum of natural numbers until the last term of the prior series, which is (turns-1)*k.
- Continue doing so until the total is less than N; if it exceeds N, distribute candies as evenly as feasible. When everyone obtains the appropriate quantity of candies in a turn, we call it a completed turn.
#SPJ3