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.
1function distributeCandies(candies, num_people) {
2 const result = new Array(num_people).fill(0);
3 let i = 0;
4 let amount = 1;
5 while (candies > 0) {
6 result[i % num_people] += Math.min(candies, amount);
7 candies -= amount;
8 amount++;
9 i++;
10 }
11 return result;
12}
13
14// Example usage:
15let candies = 7;
16let num_people = 4;
17console.log(distributeCandies(candies, num_people));
This JavaScript solution uses a fill operation on an array to handle candy distribution among people. Looping with a counter controls the sequence of distribution while Math.min prevents overallocation.
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#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> distributeCandies(int candies, int num_people) {
vector<int> result(num_people, 0);
int i;
for (i = 0; candies > 0; i++) {
int give = i + 1;
if (candies < give) {
give = candies;
}
result[i % num_people] += give;
candies -= give;
}
return result;
}
int main() {
int candies = 10, num_people = 3;
vector<int> result = distributeCandies(candies, num_people);
for (int num : result) {
cout << num << " ";
}
return 0;
}
A mathematical implementation optimizing the allocation process by calculating it over complete rounds first, ensuring full advancements before using iterative computations.