I have N dolls of various sizes.
I can put the smaller dolls inside the larger ones, but dolls of the exact same size cannot be placed inside each other.
I have to find the minimum number of dolls that remain when the maximum number of dolls have been packed.
Constraints
1≤N≤ 105
1 ≤ size of doll ≤ 105Output Print the minimum number of dolls after placing all smaller dolls inside the larger dolls.
Example #1
Input 2, 2, 3, 3
Output 2Explanation:
- Put the doll at index
1inside the doll at index3i.e. the doll of size two into the doll size three.- Put a doll at index
2inside the doll at index4i.e. doll of size two in size threeWe are left with two dolls of size three, which cannot be further placed inside each other. So, the output is
2.Example #2
Input 1, 2, 2, 3, 4, 5
Output 2Explanation: We can place dolls at index (1, 2, 4, 5) in the doll at index 6.
So, we will remain with two dolls of sizes two and five.
This is my code:
public int process(List<Integer> doll) {
Map<Integer, Integer> map = new TreeMap<>();
for(int key : doll) map.put(key, map.getOrDefault(key,0)+1);
List<Integer> list = new ArrayList<>(map.keySet());
int maxKey = list.get(list.size()-1);
int m = map.get(maxKey);
int result = 0;
for(int k : map.keySet()) {
if(k != maxKey) {
int p = map.get(k);
if(p > m){
result += p - m;
}
}
}
result += m;
return result;
}
Out of 7 test cases, 3 were failing, and they are HIDDEN test cases so I am not able to see those cases.
How to fix this problem?