###### tags: `leetcode`
# Question 1103. Distribute Candies to People
### Description:
We distribute some number of candies, to a row of n = num_people people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.
Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
Return an array (of length num_people and sum candies) that represents the final distribution of candies.
### Solution:
Just add on and bundary check.
### AC code
```cpp=
class Solution {
public:
vector<int> distributeCandies(int candies, int num_people) {
vector<int> ret(num_people, 0);
int current = 1, app = 0, index = 0;
while(candies - app > 0){
if(current > candies-app)
ret[index%num_people] += candies-app;
else
ret[index%num_people] += current;
app+=current;
current++;
index++;
}
return ret;
}
};
```
```c=
#include <stdlib.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* distributeCandies(int candies, int num_people, int* returnSize){
int current = 1;
int* ans;
ans = (int*)malloc(num_people*sizeof(int));
for(int i = 0 ; i < num_people ; i++){
ans[i] = 0;
}
*returnSize = num_people;
int index = 0, app = 0;
while(candies-app > 0){
if(current > candies-app)
ans[index%num_people] += candies - app;
else
ans[index%num_people]+=current;
app += current;
current++;
index++;
}
return ans;
}
```