Distribute Candies Problem
Description
LeetCode Problem 575.
Alice has n candies, where the i^th 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.
Example 1:
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:
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:
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 <= 10^4
- nis even.
- -10^5 <= candyType[i] <= 10^5
Solution
Approach: Count Distinct Types
Alice may eat exactly n / 2 candies, and each different type she eats adds one to the answer. Two limits apply at the same time:
- She cannot eat more types than exist. If there are
kdistinct types, the answer is at mostk. - She cannot eat more than
n / 2candies, so the answer is at mostn / 2.
Both limits can be reached together: pick one candy of each of min(k, n / 2) different types. If k < n / 2, she fills the rest of her n / 2 candies with duplicates, which do not change the count.
So the steps are:
- Put every candy type into a hash set; its size is
k. - Return
min(k, n / 2).
Example 3 shows why the minimum matters: she may eat 2 candies, but there is only 1 type, so the answer is 1.
Complexity: O(n) time and O(n) space for the set, where n is the length of candyType.
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
distinct_types = len(set(candyType))
allowed = len(candyType) // 2 # how many candies Alice may eat
return min(distinct_types, allowed)
Now write it from memory
Close the write-up and solve it yourself against the tests.