C++ 2-method Brute / DP Clean code + explanation
Method 1: Brute Force (Faster ironically)\nWe will iterate through the array looking for longest cycle that we can have by keeping a check of visited elements u
# Method 1: Brute Force (Faster ironically)\nWe will iterate through the array looking for **longest cycle** that we can have by **keeping a check of visited elements** using a bool array.\nfor ex- \nArray : [ 5 , 4 , 0 , 3 , 1 , 6 , 2 ]\nIndex:    0   1   2  3   4   5   6\nYou can see if we start** iterating from left** we get cycles , we just have to keep track of **count of longest cycle** and visited elements we will **stop a cycle if a[i]** is any **already visited** element\n0-->5-->6-->2-->**X** ( mark 0, 5 6 2 visited )\n1-->4-->**X**\n3-->**X**\n\nAs we can see 1st iteration give us maximum answer i.e. 4\n\n# Code: \n\n    int arrayNesting(vector<int>& a) {\n        int ans=0,count,n=a.size(),x;\n        vector<bool> visited(n,false);\n        for(int i=0;i<n;i++)\n        {\n            count=0;\n            x=i;\n            while(!visited[x])\n            {\n                visited[x]=true;\n                x=a[x];\n                count++;\n            }\n                \n            ans=max(ans,count); \n        }\n        \n        return ans;\n    }\n};\n\n Here\'s the link for 2nd approach:\n https://leetcode.com/explore/challenge/card/september-leetcoding-challenge-2021/636/week-1-september-1st-september-7th/3960/discuss/1438915/C++-2-method-Brute-DP-Clean-code-+-explanation
[]