1104-Fractions II

Time:2019-8-14

Preface

Weekly Contest 143 Confectionery II

Sit in rows and divide candy.

We bought some candy.candiesI’m going to divide them up in line.n = num_peopleA little friend.

For the first child1A candy, the second child2Ke, and so on, until you give it to the last childnA candy.

Then, we go back to the starting point of the team and give the first child.n + 1A candy, the second childn + 2Ke, and so on, until you give it to the last child2 * nA candy.

Repeat the process (giving one more candy each time than the last time, starting from the beginning of the team again when we reach the end of the team) until we have finished distributing all the candies. Note that even if we don’t have enough candy left in our hands (not more than the previous one), all of these candies will be distributed to current children.

Return a length ofnum_peopleThe sum of elementscandiesArray to represent the final distribution of candy (i.e.ans[i]RepresentsiThe number of candies a child gets.

Example 1:

Input: candies = 7, num_people = 4
Output: [1, 2, 3, 1]
Explanation:
For the first time, ans [0] += 1, the array becomes [1, 0, 0, 0].
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 final array becomes [1, 2, 3, 1].

Example 2:

Input: candies = 10, num_people = 3
Output: [5, 2, 3]
Explanation:
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].

Tips:

  • 1 <= candies <= 10^9
  • 1 <= num_people <= 1000

Thoughts on Problem Solving

This topic is very simple, specific logic as long as you look at the implementation code and supporting notes.

Implementation code

/**
     * 1104. Confectionery II
     * @param candies
     * @param num_people
     * @return
     */
    public int[] distributeCandies(int candies, int num_people) {
        int[] result=new int[num_people];
        // Current traversal index
        int index=0;
        // Number of candies distributed to individuals
        int num=1;
        while (candies>0){
            // Hand out candy to children
            result[index]+=num;
            // Decrease in the number of remaining candies
            candies-=num;
            // Is it sent to the last child in the team?
            if(index<num_people-1){
                ++index;
            }else{
                index=0;
            }
            // Can the number of remaining candies still be issued in accordance with the rules?
            if(candies>num){
                ++num;
            }else{
                num=candies;
            }
        }
        return result;
    }