leetcode 1103. Sub-candy||

Topic: Sit in rows and divide candy.

We bought some candy candies and plan to distribute them to n = num_people children in the queue.

Give 1 candy to the first child, 2 candy to the second child, and so on, until you give n candy to the last child.

Then, we return to the starting point of the team and give the first child n + 1 candy, the second child n + 2, and so on, until the last child 2 * n candy.

Repeat the above process (each time one more candy is given than the last time, and when the end of the line is reached, start from the beginning of the line again) until we have divided all the candies. Note that even if there are not enough candies left in our hands (not more than the number of candies sent last time), all of these candies will be distributed to the current children.

Return an array whose length is num_people and the sum of elements is candies to indicate the final distribution of candies (that is, ans[i] represents the number of candies distributed by the i-th child).

Source: LeetCode
Link: https://leetcode-cn.com/problems/distribute-candies-to-people
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Code

class Solution {
    
    
    public int[] distributeCandies(int candies, int num_people) 
    {
    
    
        int [] ans = new int[num_people];
        int index = 0;int counts = 1;
        while (candies - counts >= 0){
    
    
            ans[index++%num_people] += counts;
            candies -= counts++;
        }
        ans[index%num_people] += candies;
        return ans;
    }
}

First create an array, the length is equal to the number of people, index is the position where the candies should be divided currently, and counts is the number of candies currently to be divided, until the end of the cycle is finished;

Guess you like

Origin blog.csdn.net/qq_45789385/article/details/102747185