Maximum element in connected component of given node for Q queries | Function to perform the find operation to find the parent of a disjoint set ; FUnction to perform union operation of disjoint set union ; If the rank are the same ; Update the maximum value ; Function to find the maximum element of the set which belongs to the element queries [ i ] ; Stores the parent elements of the sets ; Stores the rank of the sets ; Stores the maxValue of the sets ; Update parent [ i ] and maxValue [ i ] to i ; Add arr [ i ] [ 0 ] and arr [ i ] [ 1 ] elements to the same set ; Find the parent element of the element queries [ i ] ; Print the maximum value of the set which belongs to the element P ; Driver Code
function Find ( parent , a ) { return ( parent [ a ] = parent [ a ] == a ? a : Find ( parent , parent [ a ] ) ) ; } function Union ( parent , rank , maxValue , a , b ) { a = Find ( parent , a ) ; b = Find ( parent , b ) ; if ( a == b ) return ; if ( rank [ a ] == rank [ b ] ) { rank [ a ] ++ ; } if ( rank [ a ] < rank [ b ] ) { let temp = a ; a = b ; b = temp ; } parent [ b ] = a ; maxValue [ a ] = Math . max ( maxValue [ a ] , maxValue [ b ] ) ; } function findMaxValueOfSet ( arr , queries , R , N , M ) { let parent = new Array ( R + 1 ) ; let rank = new Array ( R + 1 ) . fill ( 0 ) ; let maxValue = new Array ( R + 1 ) ; for ( let i = 1 ; i < R + 1 ; i ++ ) { parent [ i ] = maxValue [ i ] = i ; } for ( let i = 0 ; i < N ; i ++ ) { Union ( parent , rank , maxValue , arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } for ( let i = 0 ; i < M ; i ++ ) { let P = Find ( parent , queries [ i ] ) ; document . write ( maxValue [ P ] + " " ) ; } } let R = 5 ; let arr = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 4 , 5 ] , ] ; let queries = [ 2 , 4 , 1 , 3 ] ; let N = arr . length ; let M = queries . length ; findMaxValueOfSet ( arr , queries , R , N , M ) ;