You find some necklaces and each necklace comprises a number of beads. Unfortunately, they are tangled together.
You have numbered all the beads with numbers in the range [0..N−1], so that each number corresponds to exactly one bead. Then, for each bead, you have found the number of the next bead following it.
This information is given as an array of integers, indexed by bead numbers, and the elements are the numbers of the following beads. Each bead number appears in the array exactly once.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers, as described above, returns the maximum number of beads in a single necklace. The function should return 0 if the array is empty.
For example, given array A such that:
A[0] = 5
A[1] = 4
A[2] = 0
A[3] = 3
A[4] = 1
A[5] = 6
A[6] = 2
the function should return 4, because there are 3 necklaces:
{5, 6, 2, 0}
{4, 1}
{3}
And the longest one contains four beads.
In summary, given an array representing the order of beads in necklaces, find the necklace containing the largest number of beads.
int maxBeads(int[] A) {
}