Distribute Candies
Problem
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
The sister has two different kinds of candies, the brother has only one kind of candies.
Note:
The length of the given array is in range [2, 10,000], and will be even. The number in given array is in range [-100,000, 100,000].
Solution
public class Solution {
public int distributeCandies(int[] candies) {
Arrays.sort(candies); //Sort if given array is not sorted
Map<Integer, Integer> map = new HashMap<>();
for (int candy : candies) map.put(candy, map.getOrDefault(candy, 0) + 1);
return map.size() >= candies.length / 2 ? candies.length / 2: map.size();
}
}
Same idea - Optimal 1: Use Set instead of Map
public class Solution {
public int distributeCandies(int[] candies) {
Arrays.sort(candies); //Sort if given array is not sorted
Set<Integer> set = new HashSet<>();
for (int candy : candies) set.add(candy);
return set.size() >= candies.length / 2 ? candies.length / 2: set.size();
}
}
Same idea - Optimal 2: Earlier Termination
public class Solution {
public int distributeCandies(int[] candies) {
Arrays.sort(candies); //Sort if given array is not sorted
Set<Integer> set = new HashSet<>();
for (int candy : candies) {
set.add(candy);
if (set.size() >= candies.length / 2) return candies.length / 2;
}
return set.size();
}
}
Analysis
This is a great example of coming up optimal solutions for the same problem
In the original solution, we use HashMap
to store the kind and its count in the map
At the end, we just need to check whether the size of map is >= candies.length / 2
Because in no matter what situation, the max one can get is half of candies' sum (Problem requires even distribution)
Therefore, when we find map.size()
is >= candies.length / 2
we just return the candies.length / 2
Otherwise, we return the actual size of map, because that's max kinds one can get
One of the most important approaches in this problem is to think about the # of kind of candies first
If we think about too much about the total # of candies, we will simply get confused
So think just the # of kinds, since that's what we need to return at the end