✔✔ Array Nesting with Clear Explanation
\n-> Starting at i = 0.\nA[0] = 5;   // A[i] == A[0]\nA[5] = 6;   // A[A[i]] == A[A[0]] == A[5]\nA[6] = 2;   // A[A[A[i]]] == A[A[A[0]]] == A[A[5]] == A[6]\nA[2
```\n-> Starting at i = 0.\nA[0] = 5;   // A[i] == A[0]\nA[5] = 6;   // A[A[i]] == A[A[0]] == A[5]\nA[6] = 2;   // A[A[A[i]]] == A[A[A[0]]] == A[A[5]] == A[6]\nA[2] = 0;   // and so on\u2026\nA[0] = 5;   // We reach the start point hence S = 4 elements\n\n-> Starting at i = 1.\nA[1] = 4;   // A[i] == A[1]\nA[4] = 1;   // A[A[i]] == A[A[1] == A[4]\nA[1] = 4;   // We reach the start point hence S = 2 elements\n```\nAs per the problem statement, out of all these sets possible, we need to give the highest number of elements in such a set.\n\nA brute force solution would be to start at each of the indices and try to form sets. We can keep a track of the largest set formed and then return the result.\nLooking at the problem closely can hint at a better solution.\n\nLet us look at the array once again, when we start from i = 0.\n\n![Array Nesting Image](https://i1.wp.com/studyalgorithms.com/wp-content/uploads/2019/06/Screen-Shot-2019-06-03-at-1.33.40-AM.png?w=780&ssl=1)\n\nWe see that we form a kind of cycle.\nA similar cycle is seen when we start from i = 1.\n\n![Array Nesting Image 2](https://i0.wp.com/studyalgorithms.com/wp-content/uploads/2019/06/Screen-Shot-2019-06-03-at-1.35.01-AM.png?w=703&ssl=1)\n\nSo, this means that we will get the same set S if we start from positions (0, 2, 5, 6). Because we are forming a cycle.\n\nHence, we should try to leverage this fact and form a solution. While evaluating the set S, we can mark the elements of the array as visited. In the next iteration, if the element is already visited, we do not need to evaluate the set S again.\n\n***UPDATE** For marking an element, we can change its value to -1.*\n\n***Java Solution***\n```\npublic int arrayNesting(int[] nums) {\n\n    // boolean[] visited = new boolean[nums.length];\n    int res = 0;\n\n    for (int i = 0; i < nums.length; i++) {\n      if (nums[i]!=-1) {\n        int start = nums[i];\n        int count = 0;\n        do {\n          start = nums[start];\n          count++;\n\t\t  nums[i] = -1;\n          // visited[start] = true;\n        }\n        while (start != nums[i]);\n        res = Math.max(res, count);\n      }\n    }\n    return res;\n  }\n```\n\n***C++ Solution***\n```\nint arrayNesting(vector<int>& nums) {\n        int n = nums.size();\n        // vector<bool> visited(n,false);\n        int res=0,tmp,cnt=0;\n        for(int i=0;i<n;i++){\n            if(nums[i]!=-1){\n                tmp = nums[i];\n                cnt=0;\n                do{\n                    nums[i]=-1;\n                    tmp = nums[tmp];\n                    cnt++;\n                }while(tmp!=nums[i]);\n                res = max(res,cnt);\n            }\n        }\n        return res;\n    }\n```\n\nTime Complexity: **O(n)**\nSpace Complexity: **O(1)**\n
['C', 'Java']