Maximum Sum of Edge Values in a Graph Problem
Description
LeetCode Problem 3547.
You are given an undirected connected graph of n nodes, numbered from 0 to n - 1. Each node is connected to at most 2 other nodes.
The graph consists of m edges, represented by a 2D array edges, where edges[i] = [a_i, b_i] indicates that there is an edge between nodes a_i and b_i.
You have to assign a unique value from 1 to n to each node. The value of an edge will be the product of the values assigned to the two nodes it connects.
Your score is the sum of the values of all edges in the graph.
Return the maximum score you can achieve.
Example 1:

Input: n = 4, edges = [[0,1],[1,2],[2,3]]
Output: 23
Explanation:
The diagram above illustrates an optimal assignment of values to nodes. The sum of the values of the edges is: (1 * 3) + (3 * 4) + (4 * 2) = 23.
Example 2:

Input: n = 6, edges = [[0,3],[4,5],[2,0],[1,3],[2,4],[1,5]]
Output: 82
Explanation:
The diagram above illustrates an optimal assignment of values to nodes. The sum of the values of the edges is: (1 * 2) + (2 * 4) + (4 * 6) + (6 * 5) + (5 * 3) + (3 * 1) = 82.
Constraints:
1 <= n <= 5 * 10^4m == edges.length1 <= m <= nedges[i].length == 20 <= a_i, b_i < na_i != b_i- There are no repeated edges.
- The graph is connected.
- Each node is connected to at most 2 other nodes.
Solution
Approach: Greedy Placement on a Path or Cycle
Every node has at most two neighbours and the graph is connected, so it is either a path (n - 1 edges) or a cycle (n edges). Large values should be next to other large values.
Put n in the middle, give n - 1 to its right, n - 2 to its left, n - 3 further right, n - 4 further left, and so on, alternating sides. Every large number is then next to the next-large numbers, and 1 ends up at one end. The score is the sum of products of neighbours in this order; for a cycle also add the product of the two ends, because they are joined by the last edge. Only the number of edges matters, not which labels are connected, since any assignment of values to nodes is allowed.
Complexity: O(n) time and O(n) extra space.
class Solution:
def maxScore(self, n: int, edges: List[List[int]]) -> int:
# the graph is connected with degree <= 2: a path (n - 1 edges) or a cycle (n edges)
# put n in the middle and give the next largest values alternately to its right and left
left, right = [], [n]
for v in range(n - 1, 0, -1):
if (n - v) % 2 == 1:
right.append(v)
else:
left.append(v)
seq = left[::-1] + right
ans = sum(seq[i] * seq[i + 1] for i in range(n - 1))
if len(edges) == n: # a cycle: close it
ans += seq[0] * seq[-1]
return ans