Maximum absolute difference between any two level sum in a N | Function to find the maximum absolute difference of level sum ; Create the adjacency list ; Initialize value of maximum and minimum level sum ; Do Level order traversal keeping track of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Update the maximum level sum value ; Update the minimum level sum value ; Return the result ; Number of nodes and edges ; Edges of the N - ary tree ; Given cost ; Function call
function maxAbsDiffLevelSum ( N , M , cost , Edges ) { let adj = new Array ( N ) ; for ( let i = 0 ; i < adj . length ; i ++ ) adj [ i ] = [ ] ; for ( let i = 0 ; i < M ; i ++ ) { let u = Edges [ i ] [ 0 ] ; let v = Edges [ i ] [ 1 ] ; adj [ u ] . push ( v ) ; } let maxSum = cost [ 0 ] , minSum = cost [ 0 ] ; let q = [ ] ; q . push ( 0 ) ; while ( q . length != 0 ) { let count = q . length ; let sum = 0 ; while ( count -- > 0 ) { let temp = q [ 0 ] ; q . shift ( ) ; sum = sum + cost [ temp ] ; for ( let i = 0 ; i < adj [ temp ] . length ; i ++ ) { q . push ( adj [ temp ] [ i ] ) ; } } maxSum = Math . max ( sum , maxSum ) ; minSum = Math . min ( sum , minSum ) ; } document . write ( Math . abs ( maxSum - minSum ) ) ; } let N = 10 , M = 9 ; let Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] ; let cost = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] ; maxAbsDiffLevelSum ( N , M , cost , Edges ) ;