Longest subset of nested elements from a given array | 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
function arrayNesting ( arr ) { let res = 0 ; for ( let i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] == i ) { res = Math . max ( res , 1 ) ; } else { let count = 0 ; let curr_index = i ; while ( arr [ curr_index ] != curr_index ) { let next_index = arr [ curr_index ] ; arr [ curr_index ] = curr_index ; curr_index = next_index ; count ++ ; } res = Math . max ( res , count ) ; } } return res ; } let arr = [ 5 , 4 , 0 , 3 , 1 , 6 , 2 ] ; let res = arrayNesting ( arr ) ; document . write ( res ) ;