Sponsored
Sponsored
The goal is to find the maximum number of unique types of candies Alice can eat. We can take the following steps:
maxCandies = n / 2
.maxCandies
.Time Complexity: O(n) because we iterate over the array to create the set.
Space Complexity: O(n) for storing the unique types in a set.
1function distributeCandies(candyType) {
2 const uniqueCandies = new Set(candyType);
3 return Math.min(uniqueCandies.size, candyType.length / 2);
4}
This JavaScript solution uses a Set to derive the unique candy types, then returns the min between the size of the set and half of the candy array length, which is the maximum Alice can eat.
For another perspective:
n / 2
.Time Complexity: O(n) for creating the counter.
Space Complexity: O(n) for storing unique types in the counter.
1
This C solution uses an array as a frequency map, utilizing offsets for negative candy IDs. The unique count and check against n / 2
determine the result.