Maximum absolute difference between any two level sum in a N-ary Tree
Last Updated :
30 Jan, 2023
Given an N-ary Tree having N nodes with positive and negative values and (N – 1) edges, the task is to find the maximum absolute difference of level sum in it.
Examples:
Input: N = 8, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}}, Value[] = {4,2, 3, -5,-1, 3, -2, 6}, Below is the graph:
Output: 6
Explanation:
Sum of all nodes of 0th level is 4.
Sum of all nodes of 1st level is 0.
Sum of all nodes of 2nd level is 6.
Hence, maximum absolute difference of level sum = (6 – 0) = 6.
Input: N = 10, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}, {6, 8}, {6, 9}}, Value[] = {1, 2, -1, 3, 4, 5, 8, 6, 12, 7}, Below is the graph:
Output: 24
Approach: To find the maximum absolute difference of level sum, first find the maximum level sum and minimum level sum because the absolute difference of maximum level sum and minimum level sum always gives us maximum absolute difference i.e.,
Maximum absolute difference = abs(Maximum level sum – Minimum level sum)
Below are the steps:
- Perform the BFS Traversal on the given N-ary tree.
- While doing the BFS traversal, process nodes of different levels separately.
- For every level being processed, compute the sum of nodes in the level and keep track of maximum and minimum level sum.
- After the above traversal, find the absolute difference of maximum and minimum level sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void maxAbsDiffLevelSum( int N, int M,
vector< int > cost,
int Edges[][2])
{
vector< int > adj[N];
for ( int i = 0; i < M; i++) {
int u = Edges[i][0];
int v = Edges[i][1];
adj[u].push_back(v);
}
int maxSum = cost[0], minSum = cost[0];
queue< int > q;
q.push(0);
while (!q.empty()) {
int count = q.size();
int sum = 0;
while (count--) {
int temp = q.front();
q.pop();
sum = sum + cost[temp];
for ( int i = 0;
i < adj[temp].size(); i++) {
q.push(adj[temp][i]);
}
}
maxSum = max(sum, maxSum);
minSum = min(sum, minSum);
}
cout << abs (maxSum - minSum);
}
int main()
{
int N = 10, M = 9;
int Edges[][2] = { { 0, 1 }, { 0, 2 },
{ 0, 3 }, { 1, 4 },
{ 1, 5 }, { 3, 6 },
{ 6, 7 }, { 6, 8 },
{ 6, 9 } };
vector< int > cost = { 1, 2, -1, 3, 4,
5, 8, 6, 12, 7 };
maxAbsDiffLevelSum(N, M, cost, Edges);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void maxAbsDiffLevelSum( int N, int M,
int []cost,
int Edges[][])
{
@SuppressWarnings ( "unchecked" )
Vector<Integer> []adj = new Vector[N];
for ( int i = 0 ; i < adj.length; i++)
adj[i] = new Vector<Integer>();
for ( int i = 0 ; i < M; i++)
{
int u = Edges[i][ 0 ];
int v = Edges[i][ 1 ];
adj[u].add(v);
}
int maxSum = cost[ 0 ], minSum = cost[ 0 ];
Queue<Integer> q = new LinkedList<Integer>();
q.add( 0 );
while (!q.isEmpty())
{
int count = q.size();
int sum = 0 ;
while (count-- > 0 )
{
int temp = q.peek();
q.remove();
sum = sum + cost[temp];
for ( int i = 0 ;
i < adj[temp].size();
i++)
{
q.add(adj[temp].get(i));
}
}
maxSum = Math.max(sum, maxSum);
minSum = Math.min(sum, minSum);
}
System.out.print(Math.abs(maxSum - minSum));
}
public static void main(String[] args)
{
int N = 10 , M = 9 ;
int Edges[][] = { { 0 , 1 }, { 0 , 2 },
{ 0 , 3 }, { 1 , 4 },
{ 1 , 5 }, { 3 , 6 },
{ 6 , 7 }, { 6 , 8 },
{ 6 , 9 } };
int []cost = { 1 , 2 , - 1 , 3 , 4 ,
5 , 8 , 6 , 12 , 7 };
maxAbsDiffLevelSum(N, M, cost, Edges);
}
}
|
Python3
from collections import deque
def maxAbsDiffLevelSum(N, M, cost, Edges):
adj = [[] for i in range (N)]
for i in range (M):
u = Edges[i][ 0 ]
v = Edges[i][ 1 ]
adj[u].append(v)
maxSum = cost[ 0 ]
minSum = cost[ 0 ]
q = deque()
q.append( 0 )
while len (q) > 0 :
count = len (q)
sum = 0
while (count):
temp = q.popleft()
sum = sum + cost[temp]
for i in adj[temp]:
q.append(i)
count - = 1
maxSum = max ( sum , maxSum)
minSum = min ( sum , minSum)
print ( abs (maxSum - minSum))
if __name__ = = '__main__' :
N = 10
M = 9
Edges = [ [ 0 , 1 ], [ 0 , 2 ],
[ 0 , 3 ], [ 1 , 4 ],
[ 1 , 5 ], [ 3 , 6 ],
[ 6 , 7 ], [ 6 , 8 ],
[ 6 , 9 ] ]
cost = [ 1 , 2 , - 1 , 3 , 4 ,
5 , 8 , 6 , 12 , 7 ]
maxAbsDiffLevelSum(N, M, cost, Edges)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void maxAbsDiffLevelSum( int N, int M,
int []cost,
int [,]Edges)
{
List< int > []adj = new List< int >[N];
for ( int i = 0; i < adj.Length; i++)
adj[i] = new List< int >();
for ( int i = 0; i < M; i++)
{
int u = Edges[i, 0];
int v = Edges[i, 1];
adj[u].Add(v);
}
int maxSum = cost[0], minSum = cost[0];
Queue< int > q = new Queue< int >();
q.Enqueue(0);
while (q.Count!=0)
{
int count = q.Count;
int sum = 0;
while (count-- > 0)
{
int temp = q.Peek();
q.Dequeue();
sum = sum + cost[temp];
for ( int i = 0; i < adj[temp].Count; i++)
{
q.Enqueue(adj[temp][i]);
}
}
maxSum = Math.Max(sum, maxSum);
minSum = Math.Min(sum, minSum);
}
Console.Write(Math.Abs(maxSum - minSum));
}
public static void Main(String[] args)
{
int N = 10, M = 9;
int [,]Edges = {{0, 1}, {0, 2},
{0, 3}, {1, 4},
{1, 5}, {3, 6},
{6, 7}, {6, 8},
{6, 9}};
int []cost = {1, 2, -1, 3, 4,
5, 8, 6, 12, 7};
maxAbsDiffLevelSum(N, M, cost, Edges);
}
}
|
Javascript
<script>
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);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...