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
def arrayNesting ( arr ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if arr [ i ] == i : NEW_LINE INDENT res = max ( res , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE curr_index = i NEW_LINE while arr [ curr_index ] != curr_index : NEW_LINE INDENT next_index = arr [ curr_index ] NEW_LINE arr [ curr_index ] = curr_index NEW_LINE curr_index = next_index NEW_LINE count += 1 NEW_LINE DEDENT DEDENT res = max ( res , count ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 0 , 3 , 1 , 6 , 2 ] NEW_LINE res = arrayNesting ( arr ) NEW_LINE print ( res ) NEW_LINE DEDENT