[LeetCode] Rabbits in Forest

781. Rabbits in Forest

There is a forest with an unknown number of rabbits. We asked n rabbits “How many rabbits have the same color as you?” and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.

Given the array answers, return the minimum number of rabbits that could be in the forest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int numRabbits(vector<int>& answers) {
unordered_map<int, int> freq;
for(auto& a : answers) freq[a]++;
int res = 0;

for(auto& [k, v] : freq) {
int req = k + 1;
res += max(1.0, ceil(1.0 * v / req)) * req;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/LeetCode/rabbits-in-forest/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.