Open in App
Not now

# Maximum sum of a Node with any number of neighbours in given Graph

• Last Updated : 06 Mar, 2023

Given an array vals[] of size N, where each element represents the value of each node (0 â‰¤ index â‰¤ N-1) and an array Edges[] representing the connections between the nodes. The task is to find a node that is having the maximum sum of itself with any number of adjacent nodes.

Examples:

Input:  vals[] = {1, 2, 3, 4, 10, -10, -20}, edges[] = {[0, 1], [1, 2], [1, 3], [3, 4], [3, 5], [3, 6]}

Example 1

Output: 16
Explanation: The subgraph with the maximum sum is centered at node number 3 and includes its neighbors 1 and 4. It can be shown it is not possible to get a subgraph with a sum greater than 16.

Input: vals[] = [-5], edges[] = []
Output: -5

Approach:  The problem can be solved based on the following idea:

This problem can be solved using Greedy Algorithm, and the concept of Graph. Just calculate the sum of  vertices for each node having value greater than 0. And calculate the node having maximum value.

Follow the steps for the implementation of the above approach:

• Create a NodeSum list and add values of the node’s neighbours that are having a positive value.
• Initialise ans as minimum possible Integer.
• For every node update ans as the maximum of the current ans value and the sum of positive neighbor nodes of the current node and value of the current node.
• In the end, we will get the desired answer.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;`   `// Function to calculate the node having` `// maximum value` `int` `maxMasterGraphSum(vector<``int``>& val,` `                      ``vector >& edges)` `{` `    ``// Store the maximum value for each node` `    ``vector<``int``> NodeSum(val.size());` `    ``for` `(``int` `i = 0; i < edges.size(); i++) {` `        ``if` `(val[edges[i][0]] > 0) {` `            ``NodeSum[edges[i][1]] += val[edges[i][0]];` `        ``}` `        ``if` `(val[edges[i][1]] > 0) {` `            ``NodeSum[edges[i][0]] += val[edges[i][1]];` `        ``}` `    ``}`   `    ``// To store the maximum value` `    ``int` `ans = INT_MIN;` `    ``for` `(``int` `i = 0; i < NodeSum.size(); i++) {` `        ``ans = max(ans, NodeSum[i] + val[i]);` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``vector<``int``> vals = { 1, 2, 3, 4, 10, -10, -20 };` `    ``vector > edges` `        ``= { { 0, 1 }, { 1, 2 }, { 1, 3 }, { 3, 4 }, { 3, 5 }, { 3, 6 } };`   `    ``// Function call` `    ``cout << maxMasterGraphSum(vals, edges) << endl;`   `    ``return` `0;` `}`

## Python3

 `import` `sys`   `# Function to calculate the node having` `# maximum value` `def` `maxMasterGraphSum(val, edges):` `    ``# Store the maximum value for each node` `    ``NodeSum ``=` `[``0``]``*``len``(val)` `    ``for` `i ``in` `range``(``len``(edges)):` `        ``if` `val[edges[i][``0``]] > ``0``:` `            ``NodeSum[edges[i][``1``]] ``+``=` `val[edges[i][``0``]]` `        ``if` `val[edges[i][``1``]] > ``0``:` `            ``NodeSum[edges[i][``0``]] ``+``=` `val[edges[i][``1``]]`   `    ``# To store the maximum value` `    ``ans ``=` `-``sys.maxsize` `    ``for` `i ``in` `range``(``len``(NodeSum)):` `        ``ans ``=` `max``(ans, NodeSum[i] ``+` `val[i])`   `    ``return` `ans`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``vals ``=` `[``1``, ``2``, ``3``, ``4``, ``10``, ``-``10``, ``-``20``]` `    ``edges ``=` `[[``0``, ``1``], [``1``, ``2``], [``1``, ``3``], [``3``, ``4``], [``3``, ``5``], [``3``, ``6``]]`   `    ``# Function call` `    ``print``(maxMasterGraphSum(vals, edges))`   `# This code is contributed by akashish__`

## Javascript

 `// Javascript code to implement the approach`   `// Function to calculate the node having` `// maximum value` `function` `maxMasterGraphSum( val, edges)` `{` `    ``// Store the maximum value for each node` `    ``let NodeSum=``new` `Array(val.length).fill(0);` `    ``for` `(let i = 0; i < edges.length; i++) {` `        ``if` `(val[edges[i][0]] > 0) {` `            ``NodeSum[edges[i][1]] += val[edges[i][0]];` `        ``}` `        ``if` `(val[edges[i][1]] > 0) {` `            ``NodeSum[edges[i][0]] += val[edges[i][1]];` `        ``}` `    ``}`   `    ``// To store the maximum value` `    ``let ans = Number.MIN_SAFE_INTEGER;` `    ``for` `(let i = 0; i < NodeSum.length; i++) {` `        ``ans = Math.max(ans, NodeSum[i] + val[i]);` `    ``}`   `    ``return` `ans;` `}`   `// Driver code` `let vals = [ 1, 2, 3, 4, 10, -10, -20 ];` `let edges = [ [ 0, 1 ], [ 1, 2 ], [ 1, 3 ], [ 3, 4 ], [ 3, 5 ], [ 3, 6 ] ];`   `// Function call` `console.log(maxMasterGraphSum(vals, edges));`

## Java

 `import` `java.util.*;`   `public` `class` `GFG {` `  `  `// Function to calculate the node having` `// maximum value` `    ``static` `int` `maxMasterGraphSum(List val, List> edges) {` `       ``// Store the maximum value for each node` `        ``int``[] nodeSum = ``new` `int``[val.size()];`   `        ``for` `(List edge : edges) {` `            ``if` `(val.get(edge.get(``0``)) > ``0``) {` `                ``nodeSum[edge.get(``1``)] += val.get(edge.get(``0``));` `            ``}` `            ``if` `(val.get(edge.get(``1``)) > ``0``) {` `                ``nodeSum[edge.get(``0``)] += val.get(edge.get(``1``));` `            ``}` `        ``}` `// To store the maximum value` `        ``int` `ans = Integer.MIN_VALUE;` `        ``for` `(``int` `i = ``0``; i < nodeSum.length; i++) {` `            ``ans = Math.max(ans, nodeSum[i] + val.get(i));` `        ``}` `        ``return` `ans;` `    ``}`   `    ``public` `static` `void` `main(String[] args) {` `        ``List vals = Arrays.asList(``1``, ``2``, ``3``, ``4``, ``10``, -``10``, -``20``);` `        ``List> edges = Arrays.asList(` `                ``Arrays.asList(``0``, ``1``),` `                ``Arrays.asList(``1``, ``2``),` `                ``Arrays.asList(``1``, ``3``),` `                ``Arrays.asList(``3``, ``4``),` `                ``Arrays.asList(``3``, ``5``),` `                ``Arrays.asList(``3``, ``6``)` `        ``);` `   ``// Function call` `        ``System.out.println(maxMasterGraphSum(vals, edges));` `    ``}` `}`   `//code by ksam24000`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `MaxMasterGraphSum {` `    ``// Function to calculate the node having maximum value` `    ``public` `static` `int` `Calculate(List<``int``> val, List> edges) {` `        ``// Store the maximum value for each node` `        ``List<``int``> nodeSum = ``new` `List<``int``>();` `        ``for` `(``int` `i = 0; i < val.Count; i++) {` `            ``nodeSum.Add(0);` `        ``}` `        `  `        ``for` `(``int` `i = 0; i < edges.Count; i++) {` `            ``if` `(val[edges[i][0]] > 0) {` `                ``nodeSum[edges[i][1]] += val[edges[i][0]];` `            ``}` `            ``if` `(val[edges[i][1]] > 0) {` `                ``nodeSum[edges[i][0]] += val[edges[i][1]];` `            ``}` `        ``}`   `        ``// To store the maximum value` `        ``int` `ans = ``int``.MinValue;` `        ``for` `(``int` `i = 0; i < nodeSum.Count; i++) {` `            ``ans = Math.Max(ans, nodeSum[i] + val[i]);` `        ``}`   `        ``return` `ans;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main() {` `        ``List<``int``> vals = ``new` `List<``int``>{ 1, 2, 3, 4, 10, -10, -20 };` `        ``List> edges = ``new` `List> {` `            ``new` `List<``int``>{ 0, 1 },` `            ``new` `List<``int``>{ 1, 2 },` `            ``new` `List<``int``>{ 1, 3 },` `            ``new` `List<``int``>{ 3, 4 },` `            ``new` `List<``int``>{ 3, 5 },` `            ``new` `List<``int``>{ 3, 6 }` `        ``};`   `        ``// Function call` `        ``Console.WriteLine(Calculate(vals, edges));` `    ``}` `}`

Output

`16`

Time Complexity: O(V+E) where V is the number of vertices and E is the number of edges
Auxiliary Space: O(V)

Related Articles:

My Personal Notes arrow_drop_up
Related Articles