Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG ) | Javascript program for the above approach ; Function to perform DFS Traversal on the given graph ; Update the value of ans ; Update the currentMin and currentMax ; Traverse the adjacency list of the node src ; Recursively call for the child node ; Function to calculate maximum absolute difference between a node and its ancestor ; Stores the adjacency list of graph ; Create Adjacency list ; Add a directed edge ; Perform DFS Traversal ; Print the maximum absolute difference ; Driver Code
var ans = 0 ; function DFS ( src , Adj , arr , currentMin , currentMax ) { ans = Math . max ( ans , Math . max ( Math . abs ( currentMax - arr [ src - 1 ] ) , Math . abs ( currentMin - arr [ src - 1 ] ) ) ) ; currentMin = Math . min ( currentMin , arr [ src - 1 ] ) ; currentMax = Math . min ( currentMax , arr [ src - 1 ] ) ; Adj [ src ] . forEach ( child => { DFS ( child , Adj , arr , currentMin , currentMax ) ; } ) ; } function getMaximumDifference ( Edges , arr , N , M ) { var Adj = Array . from ( Array ( N + 1 ) , ( ) => Array ( ) ) ; for ( var i = 0 ; i < M ; i ++ ) { var u = Edges [ i ] [ 0 ] ; var v = Edges [ i ] [ 1 ] ; Adj [ u ] . push ( v ) ; } DFS ( 1 , Adj , arr , arr [ 0 ] , arr [ 0 ] ) ; document . write ( ans ) ; } var N = 5 , M = 4 ; var Edges = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 4 , 5 ] , [ 1 , 3 ] ] ; var arr = [ 13 , 8 , 3 , 15 , 18 ] ; getMaximumDifference ( Edges , arr , N , M ) ;