Java Solution using Union Find with Path Compression and Union by Size
In this solution, int[] root is also used for managing the number of descendants by initializing it by -1.\nWhen root[i] is a negative value, then it represents
In this solution, `int[] root` is also used for managing the number of descendants by initializing it by `-1`.\nWhen `root[i]` is a negative value, then it represents that `i` is the root of the tree and also that it has `-root[i]` descendants. For example, `root[i] == -2` means that it has two descendants including the root node itself.\n\nWhen you unite two trees, you can simply add the value of a root node to the another before updating the pointer as usual.\nImagine a following case: If you unite `root[i] == -1` and `root[j] == -1` then you update `root[i]` to `(-1) + (-1) = -2` and then set `root[j]` to `i`. This exactly representing that `i` has two descendants and `j` is its child node.\n\n```\nclass Solution {\n    class UnionFind {\n        private int[] root;\n        \n        public UnionFind(int n) {\n            root = new int[n];\n            Arrays.fill(root, -1);\n        }\n        \n        public int find(int x) {\n            if(root[x] < 0) {\n                return x;\n            }\n            \n            // path compression\n            return root[x] = find(root[x]);\n        }\n        \n        public void unite(int x, int y) {\n            x = find(x);\n            y = find(y);\n            \n            if(x == y) {\n                return;\n            }\n            \n            // Union by size\n            if(size(x) < size(y)) {\n                root[y] += root[x];\n                root[x] = y;\n            } else {\n                root[x] += root[y];\n                root[y] = x;\n            }\n        }\n        \n        public int size(int x) {\n            return -root[find(x)];\n        }\n    }\n    \n    \n    public int arrayNesting(int[] nums) {\n        int n = nums.length;\n        UnionFind uf = new UnionFind(n);\n        \n        int ans = 0;\n        \n        for(int i = 0; i < n; i++) {\n            uf.unite(i, nums[i]);\n            ans = Math.max(ans, uf.size(i));\n        }\n\n        return ans;\n    }\n}\n```
['Union Find', 'Java']