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.
1import java.util.Arrays;
2
3public class CandiesDistribution {
4 public static int[] distributeCandies(int candies, int num_people) {
5 int[] result = new int[num_people];
6 int i = 0;
7 int amount = 1;
8 while (candies > 0) {
9 result[i % num_people] += Math.min(candies, amount);
10 candies -= amount;
11 amount++;
12 i++;
13 }
14 return result;
15 }
16
17 public static void main(String[] args) {
18 int candies = 7, num_people = 4;
19 int[] result = distributeCandies(candies, num_people);
20 System.out.println(Arrays.toString(result));
21 }
22}
The Java solution makes use of an integer array for storing the candy distribution. Utilizes the Math.min function for ensuring the correct amount of candies are added when fewer candies are left than typically distributed.
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.