You are given an array candyType
where each element represents a type of candy. There are n
candies in total, and n
is always even. Your task is to distribute the candies equally between a brother and a sister. The goal is to maximize the number of different types of candies that the sister can get, assuming she can only get n / 2
candies.
Important constraints:
n / 2
candies.
At first glance, it might seem like we need to carefully select which candies to give to the sister to maximize her unique types. A brute-force approach would be to try all combinations of n / 2
candies and count the unique types for each, but this would be very inefficient.
Upon closer examination, we realize that the maximum number of unique candies the sister can get is limited by two things:
n / 2
).n/2
, she can take all unique types. If there are more unique types, she can only take n/2
of them.
Let's break down the steps to solve this problem efficiently:
n / 2
, where n
is the length of candyType
.We use a set because it provides O(1) lookup and insertion time, making it efficient for counting unique elements.
Suppose candyType = [1, 1, 2, 2, 3, 3]
.
n = 6
.n / 2 = 3
candies.So, the sister can get all 3 unique types if she picks one of each type.
Let's try another example: candyType = [1, 1, 2, 3]
n = 4
.n / 2 = 2
candies.She can only get 2 unique types, since she can only take 2 candies.
Brute-force approach:
n/2
candies and counting the unique types for each.C(n, n/2)
, which is exponential.n/2
and taking the minimum is O(1).Thus, the efficient solution is O(n) time and O(k) space.
The key insight is that the sister's maximum number of unique candies is limited by both the number of candies she can take and the number of unique types available. By using a set to count unique types, we achieve an efficient O(n) solution. This approach is both simple and elegant, avoiding unnecessary complexity and brute-force enumeration.
class Solution:
def distributeCandies(self, candyType):
unique_types = set(candyType)
max_candies = len(candyType) // 2
return min(len(unique_types), max_candies)
class Solution {
public:
int distributeCandies(vector<int>& candyType) {
unordered_set<int> unique_types(candyType.begin(), candyType.end());
int max_candies = candyType.size() / 2;
return min((int)unique_types.size(), max_candies);
}
};
import java.util.HashSet;
class Solution {
public int distributeCandies(int[] candyType) {
HashSet<Integer> uniqueTypes = new HashSet<>();
for (int t : candyType) {
uniqueTypes.add(t);
}
int maxCandies = candyType.length / 2;
return Math.min(uniqueTypes.size(), maxCandies);
}
}
var distributeCandies = function(candyType) {
const uniqueTypes = new Set(candyType);
const maxCandies = candyType.length / 2;
return Math.min(uniqueTypes.size, maxCandies);
};