Distribute Candies

easy hash set greedy

Problem

Alice has n candies of various kinds. She must give half away. Maximize how many different kinds she keeps.

InputcandyType = [1,1,2,2,3,3]
Output3
She keeps n/2=3 candies; there are 3 distinct kinds.

def distribute_candies(t):
    return min(len(set(t)), len(t) // 2)
function distributeCandies(t) {
  return Math.min(new Set(t).size, t.length / 2);
}
int distributeCandies(int[] t) {
    Set s = new HashSet<>();
    for (int x : t) s.add(x);
    return Math.min(s.size(), t.length / 2);
}
int distributeCandies(vector& t) {
    unordered_set s(t.begin(), t.end());
    return min((int)s.size(), (int)t.size() / 2);
}
Time: O(n) Space: O(n)