Problem Description
Given a number of candies and a number of people, distribute the candies in a sequential manner: the first person gets 1 candy, the second gets 2, and so on until the last person. Then, the distribution resumes from the first person with the next increasing number of candies. Continue the process until all candies have been distributed. If the remaining candies are less than the expected amount for a turn, give all the remaining candies to the person in turn.
Key Insights
- Use an array to represent the candy count for each person.
- Distribute candies in rounds, where the amount given increases by 1 each time.
- Use modulo arithmetic to cycle through the people.
- In the final round, if the remaining candies are less than expected, give the remainder.
Space and Time Complexity
Time Complexity: O(√candies) — The number of iterations is proportional to the number of candies distributed, which increases roughly as the square root of the total candies. Space Complexity: O(num_people) — Only an array of size num_people is required.
Solution
We simulate the distribution process using a loop. We maintain a result list of length num_people initialized with zero. Starting from the first person, we distribute an incrementally increasing number of candies. For each turn, we calculate the amount to give (which is the current count or the remaining candies if less). We then update the corresponding position in the result array, decrease the total candy count, increment the candy value by one, and use modulo arithmetic to move to the next person. The process stops when we have no more candies to distribute.