![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
24
Time Complexity: O(N)
Auxiliary Space: O(N)