3.5 Candy II

topic

Cruncher, sub-candy.

We bought some candy candies, they are going to give queued n = num_people two children.

A child to the first confectionery, the second two children, and so on, until the last child to n pieces of candy.

Then, we go back to the starting point of the team, to the first pieces of candy children n + 1, n + 2 second child stars, and so on, until the last child to 2 * n pieces of candy.

Repeat the process (and more each time than the last given a candy, when the team arrived at the end from the beginning starting point for the team again) until we finish all the sub-candy. Note that even if the rest is not in our hands the number of candy (candy before issuing more than once), these candies will be distributed to all current children.

Returns an array of NUM_PEOPLE length, and for the elements of the candies to represent the case of candies final distribution (i.e. ANS [i] represents the number of i-th candy assigned to children).

Thinking

  • Modulo arithmetic to determine which children every issue.
  • Analyzing each candy remaining number is greater than a number of b should be made candy, if a> b, b assigned to the children candy, candy remaining ab. If a <b, are only able to send the rest of a child, then stop.

Code

class Solution {
public:
    vector<int> distributeCandies(int candies, int num_people) {
        vector<int> ans( num_people, 0 );

        int i = 1;
        while ( candies > 0) {
            ans[(i - 1) % num_people] += ( candies - i > 0 ? i : candies );
  
            candies -= i;
            ++i;
        }

        return ans;
    }
};
He published 183 original articles · won praise 43 · views 60000 +

Guess you like

Origin blog.csdn.net/m0_37822685/article/details/104668169