How to Distribute Halloween Candies in Java
The challenge
You have n
candies
, the i<sup>th</sup>
candy is of type candies[i]
.
You want to distribute the candies equally between a sister and a brother so that each of them gets n / 2
candies (n
is even). The sister loves to collect different types of candies, so you want to give her the maximum number of different types of candies.
Return the maximum number of different types of candies you can give to the sister.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
n == candies.length
2 <= n <= 10<sup>4</sup>
n
is even.-10<sup>5</sup> <= candies[i] <= 10<sup>5</sup>
The solution in Java code
Here we use a HashSet, add each of the candies, and then return the minimum size of either the set’s total size, or half of the overall candies amount.
class Solution {
public int distributeCandies(int[] candies) {
HashSet<Integer> set = new HashSet<>();
for (int candy: candies) {
set.add(candy);
}
return Math.min(set.size(), candies.length / 2);
}
}