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.
1import java.util.HashSet;
2
3public class Solution {
4 public int distributeCandies(int[] candyType) {
5 HashSet<Integer> uniqueCandies = new HashSet<>();
6 for (int candy : candyType) {
7 uniqueCandies.add(candy);
8 }
9 return Math.min(uniqueCandies.size(), candyType.length / 2);
10 }
11}
This Java solution uses a HashSet to find unique candy types, then returns the minimum of the number of unique types and n / 2
.
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.