// C# program to find Maximum
// Path sum in a N-ary Tree
using System;
using System.Collections.Generic;
class GfG {
static int maxSumRecur(int node, int prev,
List<List<int>> adj, int[] arr, ref int ans) {
int maxi1 = 0, maxi2 = 0;
// Traverse all child nodes of the current node
foreach (int v in adj[node]) {
// Skip the parent node to avoid cycles
if (v != prev) {
int val = maxSumRecur(v, node, adj, arr, ref ans);
if (val > maxi1) {
maxi2 = maxi1;
maxi1 = val;
}
else if (val > maxi2) {
maxi2 = val;
}
}
}
// Update the answer with the best path sum
ans = Math.Max(ans, arr[node - 1] + maxi1 + maxi2);
// Return the maximum path sum starting
// at this node, considering its subtree
return arr[node - 1] + maxi1;
}
static int maxSum(int[,] edges, int[] arr) {
int n = arr.Length;
List<List<int>> adj = new List<List<int>>(new List<int>[n + 1]);
// Create adjacency list
for (int i = 0; i <= n; i++) {
adj[i] = new List<int>();
}
for (int i = 0; i < edges.GetLength(0); i++) {
adj[edges[i, 0]].Add(edges[i, 1]);
adj[edges[i, 1]].Add(edges[i, 0]);
}
int ans = 0;
maxSumRecur(1, -1, adj, arr, ref ans);
return ans;
}
static void Main(string[] args) {
int[] arr = { 4, -1, -3, 5, 7, -2 };
int[,] edges = {
{ 1, 2 }, { 1, 3 }, { 2, 4 }, { 2, 5 }, { 2, 6 }
};
Console.WriteLine(maxSum(edges, arr));
}
}