#3547

Maximum Sum of Edge Values in a Graph

Hard
MathGreedyGraph TheoryGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Assign higher values to nodes that are connected by edges. This maximizes the product of connected nodes, leading to a higher score.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of node degrees from the edges.
  2. 2Step 2: Sort nodes by degree in descending order.
  3. 3Step 3: Assign values from n down to 1 based on sorted order and calculate the score.
solution.py9 lines
1def maxScoreOptimal(n, edges):
2    from collections import defaultdict
3    degree = defaultdict(int)
4    for a, b in edges:
5        degree[a] += 1
6        degree[b] += 1
7    sorted_nodes = sorted(degree.keys(), key=lambda x: -degree[x])
8    value_assignment = {node: n - i for i, node in enumerate(sorted_nodes)}
9    return sum(value_assignment[a] * value_assignment[b] for a, b in edges)

Complexity note: The complexity arises from sorting the nodes based on their degree.

  • 1Higher degree nodes should get higher values.
  • 2The graph structure (path or cycle) influences value assignment.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.