![]() |
VOOZH | about |
Given N candies and K people. In the first turn, the first person gets 1 candy, the second gets 2 candies, and so on till K people. In the next turn, the first person gets K+1 candies, the second person gets k+2 candies, and so on. If the number of candies is less than the required number of candies at every turn, then the person receives the remaining number of candies.
The task is to find the total number of candies every person has at the end.
Examples:
Input: N = 7, K = 4
Output: 1 2 3 1
Explanation: In ,the first turn, the fourth person 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
Explanation: At the second turn first one receives 4 and then we have no more candies left.
Table of Content
We can solve this problem by distributing candies in a cyclic manner. Each person receives candies incrementally: the first person gets 1, the second gets 2, and so on up to K people. In the next cycle, the first person receives K+1, the second gets K+2, and this continues until all candies are distributed.
5 2 3
Start with total candies NNN, KKK people, and a turn counter. Distribute candies in increasing order (1, 2, ..., K) while decreasing the remaining candies. After each full cycle, update the turn count and continue. If a full cycle isnβt possible, distribute the remaining candies individually. Finally, use the arithmetic progression formula for efficient distribution and output the result.
5 2 3
Use binary search to find the maximum number of complete turns, then distribute leftover candies from the last incomplete turn using a loop. Finally, apply the arithmetic progression formula to efficiently allocate candies for complete turns.
5 2 3