Distribute Candies to People

easy array simulation math

Problem

We distribute some number of candies to a row of num_people people in the following way. We give 1 candy to the first person, 2 to the second, and so on up to num_people candies to the last person. Then we go back to the start, giving num_people + 1 candies to the first person, num_people + 2 to the second, and so on. This continues, each turn giving one more candy than the last, wrapping around as needed, until we run out of candies. The last person to receive candies gets all the remaining candies, even if it is fewer than what they would otherwise be given. Return an array of length num_people showing the final count each person holds.

Inputcandies = 7, num_people = 4
Output[1, 2, 3, 1]
Hand out 1, 2, 3, then only 1 candy remains for person 4 (would be 4, but capped at 1).

def distribute_candies(candies, num_people):
    res = [0] * num_people
    give = 1
    i = 0
    while candies > 0:
        amount = min(give, candies)
        res[i % num_people] += amount
        candies -= amount
        give += 1
        i += 1
    return res
function distributeCandies(candies, numPeople) {
  const res = new Array(numPeople).fill(0);
  let give = 1, i = 0;
  while (candies > 0) {
    const amount = Math.min(give, candies);
    res[i % numPeople] += amount;
    candies -= amount;
    give += 1;
    i += 1;
  }
  return res;
}
class Solution {
    public int[] distributeCandies(int candies, int numPeople) {
        int[] res = new int[numPeople];
        int give = 1, i = 0;
        while (candies > 0) {
            int amount = Math.min(give, candies);
            res[i % numPeople] += amount;
            candies -= amount;
            give += 1;
            i += 1;
        }
        return res;
    }
}
vector<int> distributeCandies(int candies, int numPeople) {
    vector<int> res(numPeople, 0);
    int give = 1, i = 0;
    while (candies > 0) {
        int amount = min(give, candies);
        res[i % numPeople] += amount;
        candies -= amount;
        give += 1;
        i += 1;
    }
    return res;
}
Time: O(√candies) Space: O(num_people)