-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistribute Candies.java
46 lines (35 loc) · 1.35 KB
/
Distribute Candies.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// https://leetcode.com/problems/distribute-candies/
class Solution {
public void arrayToHashMap(int[] curArray, HashMap<Integer, Integer> counter) {
for (int curElem: curArray) {
// If key already exist, update its value
if (counter.containsKey(curElem)) {
counter.put(curElem, counter.get(curElem) + 1);
}
// If key doesn't exist, add it to hashmap
else {
counter.put(curElem, 1);
}
}
}
public int distributeCandies(int[] candyType) {
// If candyType is empty, return 0
if (candyType.length == 0) {return 0;}
// Create a hash map
HashMap<Integer, Integer> counter = new HashMap();
// Save unique candy types in HashMap
arrayToHashMap(candyType, counter);
// Count how many unique candies there are
int uniqueCandies = 0;
for (int curElem: counter.keySet()) {
uniqueCandies++;
}
// If uniqueCandies is less than or equal to half of candyType's size, then Alice can eat every candy type
if (uniqueCandies <= candyType.length / 2) {
return uniqueCandies;
}
else {
return candyType.length / 2;
}
}
}