Array Nesting || Easy || Beginner Friendly || 3ms || O(n)
IntuitionThe problem is asking for the longest set s[k] formed by following a cycle starting at any index k in the array nums. The array is a permutation, which
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem is asking for the longest set s[k] formed by following a cycle starting at any index k in the array nums. The array is a permutation, which means each index points to a unique index. We need to identify the length of the longest cycle that can be formed by following the values in the array starting from any index.
# Approach
<!-- Describe your approach to solving the problem. -->
1) Cycle Detection: We want to detect the cycles in the permutation formed by the indices in nums. For each index k, we start at nums[k] and continue following the indices until we return to a previously visited index, forming a cycle.

2) Memoization: To avoid recalculating the cycle length for the same index multiple times, we use dynamic programming (memoization). We maintain a dp array where dp[i] stores the length of the cycle starting from index i.

3) DFS (Depth First Search): We use a DFS-like approach to explore the cycle starting at each index. If the cycle has already been computed (i.e., dp[i] is not -1), we use the precomputed value. Otherwise, we compute the cycle length recursively.

4) Max Length: After computing the cycle length for each index, we return the maximum cycle length found.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
-> Since we process each index at most once, the time complexity is O(n), where n is the size of the array nums.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
-> Since we process each index at most once, the time complexity is O(n), where n is the size of the array nums.
# Code
```cpp []
class Solution {
public:
    int n;
    vector<int> dp;

    int dfs(int i, vector<int>& nums){
        if(i>=n) return 0;

        if(dp[i]!=-1){
            return dp[i];
        }

        dp[i]=0;

        return  dp[i] = 1+dfs(nums[i], nums);
    }

    int arrayNesting(vector<int>& nums) {
        n = nums.size();
        dp.resize(n, -1);

        for(int i=0;i<n;i++){
            if(dp[i]==-1){
                dp[i] = dfs(i, nums);
            }
        }

        return *max_element(dp.begin(), dp.end());
    }
};
```
['C++']