Longest subset of nested elements from a given array | C ++ program to implement the above approach ; Function to find length of longest subset such that subset { arr [ i ] , arr [ arr [ i ] ] , . . } ; Stores length of the longest subset that satisfy the condition ; Traverse in the array , arr [ ] ; If arr [ i ] equals to i ; Update res ; Count of elements in a subset ; Stores index of elements in the current subset ; Calculate length of a subset that satisfy the condition ; Make visited the current index ; Update curr_index ; Update count ; Update res ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int arrayNesting ( vector < int > arr ) { int res = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr [ i ] == i ) { res = max ( res , 1 ) ; } else { int count = 0 ; int curr_index = i ; while ( arr [ curr_index ] != curr_index ) { int next_index = arr [ curr_index ] ; arr [ curr_index ] = curr_index ; curr_index = next_index ; count ++ ; } res = max ( res , count ) ; } } return res ; } int main ( ) { vector < int > arr = { 5 , 4 , 0 , 3 , 1 , 6 , 2 } ; int res = arrayNesting ( arr ) ; cout << res ; }