Sponsored
Sponsored
This approach iteratively distributes candies to people in a sequence, considering one cycle at a time until all candies are allocated.
Time Complexity: O(sqrt(2 * candies)). This is because the linear sum of the sequence continues until all candies are exhausted, which resembles the behavior of an arithmetic series.
Space Complexity: O(num_people), since we maintain an array to store the number of candies for each person.
1#include <stdio.h>
2
3void distributeCandies(int candies, int num_people, int result[]) {
4 int i = 0, amount = 1;
5 while (candies > 0) {
6 result[i % num_people] += (candies >= amount) ? amount : candies;
7 candies -= amount;
8 amount++;
9 i++;
10 }
11}
12
13int main() {
14 int candies = 7, num_people = 4;
15 int result[4] = {0};
16 distributeCandies(candies, num_people, result);
17 for (int i = 0; i < num_people; i++) {
18 printf("%d ", result[i]);
19 }
20 return 0;
21}
The C solution utilizes a simple while loop for the distribution of candies. It tracks how many candies to give based on a running total. The modulo operation (%num_people) ensures allocation is cycled through the people repeatedly until candies run out.
Using a mathematical approach, calculate full rounds of distribution first to optimize the solution as opposed to simulating step-by-step distribution.
Time Complexity: O(sqrt(2 * candies)) due to converging arithmetic series.
Space Complexity: O(num_people).
1#
Although this solution follows a similar process to the iterative one, it stops calculating after wrapping through all the necessary candies in full cycles using arithmetic logic for each complete set of distributions.