Given a 2D array Edges[][], representing a directed edge between the pair of nodes in a Directed Acyclic Connected Graph consisting of N nodes valued from [1, N] and an array arr[] representing weights of each node, the task is to find the maximum absolute difference between the weights of any node and any of its ancestors.
Examples:
Input: N = 5, M = 4, Edges[][2] = {{1, 2}, {2, 3}, {4, 5}, {1, 3}}, arr[] = {13, 8, 3, 15, 18}
Output: 10
Explanation:From the above graph, it can be observed that the maximum difference between the value of any node and any of its ancestors is 18 (Node 5) – 8 (Node 2) = 10.
Input: N = 4, M = 3, Edges[][2] = {{1, 2}, {2, 4}, {1, 3}}, arr[] = {2, 3, 1, 5}
Output: 3
Approach: The idea to solve the given problem is to perform DFS Traversal on the Graph and populate the maximum and minimum values from each node to its child node and find the maximum absolute difference.
Follow the steps below to solve the given problem:
- Initialize a variable, say ans as INT_MIN to store the required maximum difference.
- Perform DFS traversal on the given graph to find the maximum absolute difference between the weights of a node and any of its ancestors by performing the following operations:
- For each source node, say src, update the value of ans to store the maximum of the absolute difference between the weight of src and currentMin and currentMax respectively.
- Update the value of currentMin as the minimum of currentMin and the value of the source node src.
- Update the value of currentMax as the maximum of currentMax and the value of the source node src.
- Now, recursively traverse the child nodes of src and update values of currentMax and currentMin as DFS(child, Adj, ans, currentMin, currentMax).
- After completing the above steps, print the value of ans as the resultant maximum difference.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to perform DFS// Traversal on the given graphvoid DFS(int src, vector<int> Adj[],         int& ans, int arr[],         int currentMin, int currentMax){Â
    // Update the value of ans    ans = max(        ans, max(abs(                     currentMax - arr[src - 1]),                 abs(currentMin - arr[src - 1])));Â
    // Update the currentMin and currentMax    currentMin = min(currentMin,                     arr[src - 1]);Â
    currentMax = min(currentMax,                     arr[src - 1]);Â
    // Traverse the adjacency    // list of the node src    for (auto& child : Adj[src]) {Â
        // Recursively call        // for the child node        DFS(child, Adj, ans, arr,            currentMin, currentMax);    }}Â
// Function to calculate maximum absolute// difference between a node and its ancestorvoid getMaximumDifference(int Edges[][2],                          int arr[], int N,                          int M){Â
    // Stores the adjacency list of graph    vector<int> Adj[N + 1];Â
    // Create Adjacency list    for (int i = 0; i < M; i++) {        int u = Edges[i][0];        int v = Edges[i][1];Â
        // Add a directed edge        Adj[u].push_back(v);    }Â
    int ans = 0;Â
    // Perform DFS Traversal    DFS(1, Adj, ans, arr,        arr[0], arr[0]);Â
    // Print the maximum    // absolute difference    cout << ans;}Â
// Driver Codeint main(){    int N = 5, M = 4;    int Edges[][2]        = { { 1, 2 }, { 2, 3 },            { 4, 5 }, { 1, 3 } };    int arr[] = { 13, 8, 3, 15, 18 };Â
    getMaximumDifference(Edges, arr, N, M);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â Â Â Â Â static int ans;Â
// Function to perform DFS// Traversal on the given graphstatic void DFS(int src,                ArrayList<ArrayList<Integer> > Adj,                int arr[], int currentMin,                int currentMax){         // Update the value of ans    ans = Math.max(ans,          Math.max(Math.abs(currentMax - arr[src - 1]),                   Math.abs(currentMin - arr[src - 1])));Â
    // Update the currentMin and currentMax    currentMin = Math.min(currentMin, arr[src - 1]);Â
    currentMax = Math.min(currentMax, arr[src - 1]);Â
    // Traverse the adjacency    // list of the node src    for(Integer child : Adj.get(src))    {                 // Recursively call        // for the child node        DFS(child, Adj, arr, currentMin, currentMax);    }}Â
// Function to calculate maximum absolute// difference between a node and its ancestorstatic void getMaximumDifference(int Edges[][],                                 int arr[], int N,                                 int M){    ans = 0;         // Stores the adjacency list of graph    ArrayList<ArrayList<Integer>> Adj = new ArrayList<>();Â
    for(int i = 0; i < N + 1; i++)        Adj.add(new ArrayList<>());Â
    // Create Adjacency list    for(int i = 0; i < M; i++)     {        int u = Edges[i][0];        int v = Edges[i][1];Â
        // Add a directed edge        Adj.get(u).add(v);    }Â
    // Perform DFS Traversal    DFS(1, Adj, arr, arr[0], arr[0]);Â
    // Print the maximum    // absolute difference    System.out.println(ans);}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int N = 5, M = 4;Â Â Â Â int Edges[][] = { { 1, 2 }, { 2, 3 }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â { 4, 5 }, { 1, 3 } };Â Â Â Â int arr[] = { 13, 8, 3, 15, 18 };Â
    getMaximumDifference(Edges, arr, N, M);}}Â
// This code is contributed by offbeat |
Python3
# Python3 program for the above approachans = 0Â
# Function to perform DFS# Traversal on the given graphdef DFS(src, Adj, arr, currentMin, currentMax):         # Update the value of ans    global ans    ans = max(ans, max(abs(currentMax - arr[src - 1]),                       abs(currentMin - arr[src - 1])))Â
    # Update the currentMin and currentMax    currentMin = min(currentMin, arr[src - 1])Â
    currentMax = min(currentMax, arr[src - 1])Â
    # Traverse the adjacency    # list of the node src    for child in Adj[src]:                 # Recursively call        # for the child node        DFS(child, Adj, arr, currentMin, currentMax)Â
# Function to calculate maximum absolute# difference between a node and its ancestordef getMaximumDifference(Edges, arr, N, M):         global ans         # Stores the adjacency list of graph    Adj = [[] for i in range(N + 1)]Â
    # Create Adjacency list    for i in range(M):        u = Edges[i][0]        v = Edges[i][1]Â
        # Add a directed edge        Adj[u].append(v)Â
    # Perform DFS Traversal    DFS(1, Adj, arr, arr[0], arr[0])Â
    # Print the maximum    # absolute difference    print(ans)Â
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â N = 5Â Â Â Â M = 4Â Â Â Â Edges = [[1, 2], [2, 3], [4, 5], [1, 3]]Â Â Â Â arr =Â [13, 8, 3, 15, 18]Â Â Â Â Â Â Â Â Â getMaximumDifference(Edges, arr, N, M)Â
# This code is contributed by ipg2016107 |
C#
// C# program for the above approachusing System;using System.Collections.Generic;class GFG {         static int ans;      // Function to perform DFS    // Traversal on the given graph    static void DFS(int src, List<List<int>> Adj, int[] arr,                     int currentMin, int currentMax)    {                  // Update the value of ans        ans = Math.Max(ans,              Math.Max(Math.Abs(currentMax - arr[src - 1]),                       Math.Abs(currentMin - arr[src - 1])));              // Update the currentMin and currentMax        currentMin = Math.Min(currentMin, arr[src - 1]);              currentMax = Math.Min(currentMax, arr[src - 1]);              // Traverse the adjacency        // list of the node src        foreach(int child in Adj[src])        {                          // Recursively call            // for the child node            DFS(child, Adj, arr, currentMin, currentMax);        }    }          // Function to calculate maximum absolute    // difference between a node and its ancestor    static void getMaximumDifference(int[,] Edges,                                      int[] arr, int N, int M)    {        ans = 0;                  // Stores the adjacency list of graph        List<List<int>> Adj = new List<List<int>>();              for(int i = 0; i < N + 1; i++)            Adj.Add(new List<int>());              // Create Adjacency list        for(int i = 0; i < M; i++)        {            int u = Edges[i,0];            int v = Edges[i,1];                  // Add a directed edge            Adj[u].Add(v);        }              // Perform DFS Traversal        DFS(1, Adj, arr, arr[0], arr[0]);              // Print the maximum        // absolute difference        Console.WriteLine(ans);    }       static void Main() {    int N = 5, M = 4;    int[,] Edges = { { 1, 2 }, { 2, 3 },                      { 4, 5 }, { 1, 3 } };    int[] arr = { 13, 8, 3, 15, 18 };      getMaximumDifference(Edges, arr, N, M);  }}Â
// This code is contributed by rameshtravel07. |
Javascript
<script>Â
// Javascript program for the above approachÂ
var ans = 0;Â
// Function to perform DFS// Traversal on the given graphfunction DFS(src, Adj, arr, currentMin, currentMax){Â
    // Update the value of ans    ans = Math.max(        ans, Math.max(Math.abs(                     currentMax - arr[src - 1]),                 Math.abs(currentMin - arr[src - 1])));Â
    // Update the currentMin and currentMax    currentMin = Math.min(currentMin,                     arr[src - 1]);Â
    currentMax = Math.min(currentMax,                     arr[src - 1]);Â
    // Traverse the adjacency    // list of the node src    Adj[src].forEach(child => {               // Recursively call        // for the child node        DFS(child, Adj,arr,            currentMin, currentMax);    });}Â
// Function to calculate maximum absolute// difference between a node and its ancestorfunction getMaximumDifference(Edges, arr, N, M){Â
    // Stores the adjacency list of graph    var Adj = Array.from(Array(N+1), ()=> Array());Â
    // Create Adjacency list    for (var i = 0; i < M; i++) {        var u = Edges[i][0];        var v = Edges[i][1];Â
        // Add a directed edge        Adj[u].push(v);    }Â
    // Perform DFS Traversal    DFS(1, Adj, arr,        arr[0], arr[0]);Â
    // Print the maximum    // absolute difference    document.write( ans);}Â
// Driver Codevar 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);Â
</script> |
10
Â
Time Complexity: O(N + M)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

