Leetcode 565 Solution

This article provides solution to leetcode question 565 (array-nesting)

https://leetcode.com/problems/array-nesting

Solution

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int visited_cnt = 0;
        int ans = 0;

        while (visited_cnt != nums.size())
        {
            for (int i = 0; i < nums.size(); i++)
            {
                if (nums[i] == -1)
                    continue;

                int start = i;
                int curr = start;
                int len = 1;

                while (start != nums[curr])
                {
                    int next = nums[curr];
                    nums[curr] = -1;
                    visited_cnt++;

                    len++;
                    curr = next;
                }
                nums[curr] = -1;
                visited_cnt++;

                ans = max(len, ans);
            }
        }

        return ans;
    }
};