luoheng
10/11/2019 - 1:21 PM

distributeCandies

func distributeCandies(candies int, num_people int) []int {
    turns, s := 0, 1
    for candies > num_people * (num_people + 2*s - 1) / 2 {
        candies -= num_people*(num_people+2*s-1)/2
        turns++
        s += num_people
    }
    res := make([]int, num_people)
    res[0] = (1 + s) * (turns + 1) / 2 - s
    if turns != 0 {
        for i := 1; i < num_people; i++ {
            res[i] = res[i-1] + turns
        }
    }
    for i := 0; i < num_people; i++ {
        if candies > s {
            res[i] += s
            candies -= s
            s++
        } else {
            res[i] += candies
            break
        }
    }
    return res
}