You are given an integer array candyType
of length n
, where candyType[i]
represents the type of the i-th candy you have. Your goal is to distribute the candies equally between you and your sibling. Return the maximum number of different types of candies you can eat if you follow the above rules.
Before moving forward with the solution, let’s clarify a few things:
How is the distribution of candies handled? Each person should get an equal number of candies.
Can the array contain duplicate types? Yes, the array can contain duplicate types of candies.
What is the maximum length (n
) of the candyType
array?
The maximum length isn’t mentioned here, but we can assume it’s within reasonable limits as per LeetCode constraints (typically up to 10^4 or 10^5).
What should I return if n
is very small or zero?
If there are no candies, the result should be 0 as you cannot eat any types of candies.
To solve this problem:
n / 2
candies. The number of types you can get would be the minimum of n / 2
(total candies you can eat) and the number of unique candy types.def distributeCandies(candyType):
# Step 1: Find the unique types of candy
unique_candies = set(candyType)
# Step 2: Each person gets n // 2 candies
max_candies_per_person = len(candyType) // 2
# Step 3: Calculate the maximum types of candies you can eat
return min(len(unique_candies), max_candies_per_person)
# Example usage:
candyType = [1, 1, 2, 2, 3, 3]
print(distributeCandies(candyType)) # Output: 3
Hence, the overall time complexity is O(n), where n
is the length of the candyType
array.
This solution is efficient and handles even the upper constraints well, given the linear complexity.
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?