largest closed loop

/*
     * A zero-indexed array A consisting of N different integers is given. The
     * array contains all integers in the range [0..N−1]. Sets S[K] for 0 ≤ K <
     * N are defined as follows: S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }. Sets
     * S[K] are finite for each K.
     *
     * Write a function:
     *
     * class Solution { public int solution(int[] A); }
     *
     * that, given an array A consisting of N integers, returns the size of the
     * largest closed loop set S[K] for this array. The function should return 0 if the
     * array is empty.
     */
    /*
     * changed value
     */
public int largestClosedLoopSet(int[] A){
    if(A == null || A.length == 0){
        return 0;
    }
    int res = 1;
    int count = 0;
    for(int i = 0; i < A.length; i++){
        count = 0;
        while(A[i] >= 0 && A[i] < A.length){
            count++;
            int nextIndex = A[i];
            // reset A[i] to prevent future repeat iteration.
            A[i] = -1;
            i = inextIndex;
        }
        res = Math.max(res, count);
    }
return res;
}

Leave a comment