Problem

Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor’s advice.

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.

Examples

Example 1:

1
2
3
Input: candyType = [1,1,2,2,3,3]
Output: 3
Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.

Example 2:

1
2
3
Input: candyType = [1,1,2,3]
Output: 2
Explanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.

Example 3:

1
2
3
Input: candyType = [6,6,6,6]
Output: 1
Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.

Constraints:

  • n == candyType.length
  • 2 <= n <= 104
  • n is even.
  • -105 <= candyType[i] <= 105

Solution

Method 1 – Hash Set for Unique Types

Intuition

The key idea is that Alice can eat at most n/2 candies, but she wants to maximize the number of different types. The answer is the minimum of the number of unique types and n/2. For example, if there are 3 unique types and she can eat 3 candies, she can eat all types. If there are 4 unique types but she can only eat 2 candies, she can only eat 2 types.

Approach

  1. Count the number of unique candy types using a set or hash table.
  2. Calculate n/2, where n is the total number of candies.
  3. The answer is the minimum of the number of unique types and n/2.

C++
1
2
3
4
5
6
7
8
9
class Solution {
public:
  int distributeCandies(vector<int>& candyType) {
    unordered_set<int> types(candyType.begin(), candyType.end());
    int n = candyType.size();
    int ans = min((int)types.size(), n / 2);
    return ans;
  }
};
Java
1
2
3
4
5
6
7
8
9
class Solution {
  public int distributeCandies(int[] candyType) {
    Set<Integer> types = new HashSet<>();
    for (int c : candyType) types.add(c);
    int n = candyType.length;
    int ans = Math.min(types.size(), n / 2);
    return ans;
  }
}
Python
1
2
3
4
5
6
class Solution:
  def distributeCandies(self, candyType: list[int]) -> int:
    types = set(candyType)
    n = len(candyType)
    ans = min(len(types), n // 2)
    return ans

Complexity

  • ⏰ Time complexity: O(N), where N is the number of candies.
  • 🧺 Space complexity: O(K), where K is the number of unique candy types.