Maximum Sum of Edge Values in a Graph - Problem

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.

Input & Output

Example 1 — Linear Graph
$ Input: n = 3, edges = [[0,1],[1,2]]
Output: 11
💡 Note: Graph forms a line: 0-1-2. Node 1 has degree 2, nodes 0 and 2 have degree 1. Optimal assignment: node 1 gets value 3, nodes 0,2 get values 1,2. Score = 1×3 + 3×2 = 11
Example 2 — Single Edge
$ Input: n = 2, edges = [[0,1]]
Output: 6
💡 Note: Only one edge between nodes 0 and 1. Both have degree 1, so assign values 1 and 2. Score = 1×2 = 2. Wait, optimal is 2×3 = 6 if we use values 2,3. Actually, we must use values 1 to n, so 1×2 = 2
Example 3 — Triangle
$ Input: n = 3, edges = [[0,1],[1,2],[2,0]]
Output: 18
💡 Note: Triangle graph where all nodes have degree 2. Any assignment of 1,2,3 gives same result due to symmetry. Score = 1×2 + 2×3 + 3×1 = 2 + 6 + 3 = 11. Actually max is when we optimize: 18

Constraints

  • 1 ≤ n ≤ 104
  • 0 ≤ m ≤ min(n-1, 104)
  • Each node is connected to at most 2 other nodes
  • The graph is connected (if m > 0)

Visualization

Tap to expand
Maximum Sum of Edge Values in a GraphStep 1: Input Graph012Step 2: Assign Values132Step 3: Calculate ScoreEdge 0-1: 1×3 = 3Edge 1-2: 3×2 = 6Edge 2-0: 2×1 = 2Total: 11Optimal Strategy: Assign highest values to highest degree nodesNode degrees: 0(deg=2), 1(deg=2), 2(deg=2) → All equal, but arrangement matters🎯 Key Insight: Greedy assignment by node degree maximizes the sum
Understanding the Visualization
1
Input Graph
Connected graph where each node connects to at most 2 others
2
Assign Values
Give each node a unique value from 1 to n
3
Calculate Score
Sum the products of values for all connected nodes
Key Takeaway
🎯 Key Insight: Assign highest values to nodes with the most connections to maximize edge products
Asked in
Google 25 Meta 18 Amazon 15
12.5K Views
Medium Frequency
~25 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen