All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0701_0800.s0781_rabbits_in_forest.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0701_0800.s0781_rabbits_in_forest;

// #Medium #Array #Hash_Table #Math #Greedy

public class Solution {
    public int numRabbits(int[] answers) {
        int[] counts = new int[1001];
        for (int element : answers) {
            counts[element]++;
        }
        int answer = counts[0];
        for (int i = 1; i <= 1000; i++) {
            if (counts[i] > 0) {
                int rabbitsInPartialGroup = counts[i] % (i + 1);
                int rabbitsInCompleteGroups = counts[i] - rabbitsInPartialGroup;
                answer += rabbitsInCompleteGroups;
                if (rabbitsInPartialGroup > 0) {
                    answer += (i + 1);
                }
            }
        }
        return answer;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy