-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0781-rabbits-in-forest.js
More file actions
36 lines (32 loc) · 899 Bytes
/
0781-rabbits-in-forest.js
File metadata and controls
36 lines (32 loc) · 899 Bytes
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
/**
* 781. Rabbits in Forest
* https://leetcode.com/problems/rabbits-in-forest/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number[]} answers
* @return {number}
*/
var numRabbits = function(answers) {
const colorGroups = {};
let totalRabbits = 0;
for (const answer of answers) {
if (answer === 0) {
totalRabbits++;
continue;
}
if (!colorGroups[answer] || colorGroups[answer] === 0) {
totalRabbits += answer + 1;
colorGroups[answer] = answer;
} else {
colorGroups[answer]--;
}
}
return totalRabbits;
};