Leetcode 1103. Distribute Candies to People
You are given candies
number of candies that you need to distribute to num_people
people. The task is to distribute the candies in the following way:
i
candies to the i-th
person.num_people
-th person, you start again from the first person and continue giving candies.You need to return an array that represents the number of candies each person gets.
result
of length equal to num_people
, initialized to 0.current_candy
to keep track of the number of candies to distribute on each turn.current_candy
, distribute all remaining candies and exit.#include <vector>
#include <iostream>
using namespace std;
vector<int> distributeCandies(int candies, int num_people) {
vector<int> result(num_people, 0); // Initialize result array with 0s
int current_candy = 1; // Start with 1 candy to distribute
int index = 0; // Start with the first person
while (candies > 0) {
if (candies < current_candy) {
result[index] += candies; // If the remaining candies are less than current_candy
break; // Exhaust all candies
} else {
result[index] += current_candy;
}
candies -= current_candy; // Decrease the remaining candies
current_candy++; // Increment the candies to distribute next time
index = (index + 1) % num_people; // Move to the next person cyclically
}
return result;
}
// Driver function for testing purposes
int main() {
int candies = 7;
int num_people = 4;
vector<int> result = distributeCandies(candies, num_people);
for (int candy : result) {
cout << candy << " ";
}
cout << endl;
return 0;
}
current_candy
increases by 1 each iteration. The sum of the first n
integers is (\frac{n(n + 1)}{2}). Therefore, the number of iterations is approximately (\sqrt{2 \times \text{candies}}). Thus, the time complexity is (O(\sqrt{\text{candies}})).num_people
, so the space complexity is (O(\text{num_people})).This code provides an efficient and clear approach to solving the problem by iteratively distributing candies in the specified manner.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?