You need to distribute n
candies to k
people in a specific way. The i-th
person gets i
candies (1-indexed) in the first round, the i-th
person gets k + i
candies in the second round, and so on until we run out of candies. The distribution process continues in rounds until all candies are distributed. Return an array representing the distribution of candies to each person.
Example:
Input: candies = 7, num_people = 4
Output: [1, 2, 3, 1]
Explanation:
On the first turn, the first person gets 1 candy, the second person gets 2 candies, the third person gets 3 candies, and the fourth person gets 1 candy (because there is only one candy left).
Note:
1 <= n <= 10^9
1 <= k <= 1000
num_people
be zero?
1 <= k
, so num_people
will always be at least 1.num_people
with all zeros. This array will store the candies distributed to each person.i
to keep track of the current number of candies to distribute and another variable index
to track the current person.i
candies to the index
-th person until candies
< i
.i
.i
by 1 to distribute in the next round.index
), using modulo operation to cycle through the people.i
, distribute all remaining candies to the current person and end.Let’s implement this step-by-step in Python.
def distributeCandies(candies, num_people):
distribution = [0] * num_people
i = 0
while candies > 0:
distribution[i % num_people] += min(candies, i + 1)
candies -= i + 1
i += 1
return distribution
distribution = [0] * num_people
to create a list of zeros of size num_people
.i
starts from 0 and increases with each iteration.min(candies, i + 1)
candies to the (i % num_people)
-th person. This ensures if candies
is less than i + 1
, we only distribute the remaining candies.i + 1
from candies
.i
by 1 to move to the next turn.candies
becomes 0 or less.The time complexity of this solution is O(sqrt(2n))
. The reason being the number of iterations i
grows until the sum of the first i
natural numbers is greater than or equal to n
, which grows roughly with the order of the square root of n
.
candies
falls below the current i + 1
.2 * n
.Thus, the time complexity is efficient and suitable for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?