Nuggets team number online, help you Offer impromptu! Click for details

1. Title Description

Sit in rows and share the candy.

We bought some candies and were going to give them to the kids in line.

Give the first child one candy, the second child two, and so on, until the last child is given n candy.

Then, we go back to the beginning of the group and give n + 1 candy to the first child, n + 2 candy to the second child, and so on until we give 2 * N candy to the last child.

Repeat the process (giving one more candy each time, starting again at the beginning when we reach the end of the line) until we have all the candy. Note that even if we don’t have enough candy left (no more than from the previous distribution), all the candy will be given to the current child.

Returns an array of num_people with the sum of candies elements to indicate the final distribution of candies (ans[I] is the number of candies distributed to the i-th child).

Example 1: Input: candies = 7, num_people = 4 Output: [1,2,3,1] The second time, ans[1] += 2, the array becomes [1,2,0,0]. The third time, ans[2] += 3, the array becomes [1,2,3,0]. The fourth time, ans[3] += 1 (because there is only one candy left), the array becomes [1,2,3,1]. For the first time, ans[0] += 1, the array becomes [1,0,0]. The second time, ans[1] += 2, the array becomes [1,2,0]. The third time, ans[2] += 3, the array becomes [1,2,3]. The fourth time, ans[0] += 4, the final array becomes [5,2,3].Copy the code

Second, train of thought analysis

The number of sweets given to the child who first knows the index position is index+1 (assuming an infinite number of sweets).

Since the candy is limited, the number of candy should be.

After this distribution, the formula is as follows: the total number of candies for children is.

Number of sweets left

AC code

public int[] distributeCandies(int candies, int num_people) {
    int[] ans = new int[num_people];
    int index = 0;
    while (candies > 0) {
        // Children in index position should get the same amount of candy as index+1. But maybe the candy doesn't have enough index+1, so you need to take the minimum
        int curObtain = Math.min(index + 1, candies);
        ans[index++ % num_people] += curObtain;
        candies -= curObtain;
    }

    return ans;
}
Copy the code