|
| 1 | +/** |
| 2 | + * 1103. Distribute Candies to People |
| 3 | + * https://leetcode.com/problems/distribute-candies-to-people/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * We distribute some number of `candies`, to a row of `n = num_people` |
| 7 | + * people in the following way: |
| 8 | + * |
| 9 | + * We then give 1 candy to the first person, 2 candies to the second |
| 10 | + * person, and so on until we give `n` candies to the last person. |
| 11 | + * |
| 12 | + * Then, we go back to the start of the row, giving `n + 1` candies to |
| 13 | + * the first person, `n + 2` candies to the second person, and so on |
| 14 | + * until we give `2 * n` candies to the last person. |
| 15 | + * |
| 16 | + * This process repeats (with us giving one more candy each time, |
| 17 | + * and moving to the start of the row after we reach the end) until |
| 18 | + * we run out of candies. The last person will receive all of our |
| 19 | + * remaining candies (not necessarily one more than the previous gift). |
| 20 | + * |
| 21 | + * Return an array (of length `num_people` and sum `candies`) that |
| 22 | + * represents the final distribution of candies. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} candies |
| 27 | + * @param {number} num_people |
| 28 | + * @return {number[]} |
| 29 | + */ |
| 30 | +var distributeCandies = function(candies, num_people) { |
| 31 | + const answer = new Array(num_people).fill(0); |
| 32 | + |
| 33 | + for (let amount = 0; candies > 0; candies -= amount) { |
| 34 | + answer[amount % num_people] += Math.min(candies, ++amount); |
| 35 | + } |
| 36 | + |
| 37 | + return answer; |
| 38 | +}; |
0 commit comments