Simulate each gift, cap it by the remaining candies, add it to the current cyclic recipient, and increase the next gift by one.
Complexity
O(sqrt(candies)) time and O(people) output space.
Distribute increasing candy amounts cyclically until no candies remain.
Simulate each gift, cap it by the remaining candies, add it to the current cyclic recipient, and increase the next gift by one.
O(sqrt(candies)) time and O(people) output space.
package main
func distributeCandies(candies int, numPeople int) []int {
result := make([]int, numPeople)
gift, person := 1, 0
for candies > 0 {
amount := gift
if candies < amount {
amount = candies
}
result[person] += amount
candies -= amount
gift++
person = (person + 1) % numPeople
}
return result
}
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> list[int]:
result = [0] * num_people; gift = 1; person = 0
while candies:
amount = min(gift, candies); result[person] += amount; candies -= amount
gift, person = gift + 1, (person + 1) % num_people
return result
function distributeCandies(candies: number, numPeople: number): number[] {
const result = new Array<number>(numPeople).fill(0); let gift = 1; let person = 0;
while (candies > 0) { const amount = Math.min(gift, candies); result[person] += amount; candies -= amount; gift += 1; person = (person + 1) % numPeople; }
return result;
}