Beats 100% users || JAVA || Best
Intuition\nThe intuition behind the solution is that since nums is a permutation of [0, n - 1], following the indices will eventually lead back to the starting 
# Intuition\nThe intuition behind the solution is that since nums is a permutation of [0, n - 1], following the indices will eventually lead back to the starting index, forming a cycle. The length of the cycle is the length of the set s. The goal is to find the maximum length of such a set s.\n\n# Approach\n1. We iterate through each element in the array.\n2. For each unvisited element (marked by nums[i] != -1), we start a cycle traversal.\n3. Within the cycle traversal, we follow the indices until we reach an already visited element (marked by setting nums[j] = -1).\n4. We keep track of the count of elements visited in the cycle.\n5. Update the maximum cycle length (ans) encountered so far.\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n    public int arrayNesting(int[] nums){\n        int ans=0;\n        for(int i=0;i<nums.length;i++){\n            if(nums[i]!=-1){\n            int j=i;\n            int count=0;\n            while(nums[j]!=-1){\n                int k=nums[j];\n                nums[j]=-1;\n                j=k;\n                count++;\n            }\n            ans=Math.max(ans,count);\n            if(ans==nums.length) return ans;\n            }\n        }\n        return ans;\n    }\n}\n```
['Java']