```
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int res = 1, size = nums.size();
for (int i = 0; i < size; ++i) {
if (nums[i] == i || nums[i] < 0) continue;
int k = i, len = 0;
while (nums[k] >= 0) {
nums[k] = -nums[k];
k = -nums[k];
++len;
}
res = max(res, len);
}
return res;
}
};
```