LeetCode #3547 — HARD

Maximum Sum of Edge Values in a Graph

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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] = [ai, bi] indicates that there is an edge between nodes ai and bi.

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 * 104
  • m == edges.length
  • 1 <= m <= n
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • There are no repeated edges.
  • The graph is connected.
  • Each node is connected to at most 2 other nodes.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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] = [ai, bi] indicates that there is an edge between nodes ai and bi. 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math · Greedy

Example 1

4
[[0,1],[1,2],[2,3]]

Example 2

6
[[0,3],[4,5],[2,0],[1,3],[2,4],[1,5]]
Step 02

Core Insight

What unlocks the optimal approach

  • The graph is either a simple path or a cycle.
  • Greedily assign values to the nodes.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3547: Maximum Sum of Edge Values in a Graph
class Solution {
  public long maxScore(int n, int[][] edges) {
    long ans = 0;
    List<Integer>[] graph = new List[n];
    List<Integer> cycleSizes = new ArrayList<>(); // components where all nodes have degree 2
    List<Integer> pathSizes = new ArrayList<>();  // components that are not cycleSizes
    boolean[] seen = new boolean[n];
    Arrays.setAll(graph, i -> new ArrayList<>());

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    for (int i = 0; i < n; ++i) {
      if (seen[i])
        continue;
      List<Integer> component = getComponent(graph, i, seen);
      final boolean allDegree2 = component.stream().allMatch(u -> graph[u].size() == 2);
      if (allDegree2)
        cycleSizes.add(component.size());
      else if (component.size() > 1)
        pathSizes.add(component.size());
    }

    for (final int cycleSize : cycleSizes) {
      ans += calculateScore(n - cycleSize + 1, n, true);
      n -= cycleSize;
    }

    Collections.sort(pathSizes, Collections.reverseOrder());

    for (final int pathSize : pathSizes) {
      ans += calculateScore(n - pathSize + 1, n, false);
      n -= pathSize;
    }

    return ans;
  }

  private List<Integer> getComponent(List<Integer>[] graph, int start, boolean[] seen) {
    List<Integer> component = new ArrayList<>(List.of(start));
    seen[start] = true;
    for (int i = 0; i < component.size(); ++i) {
      final int u = component.get(i);
      for (final int v : graph[u]) {
        if (seen[v])
          continue;
        component.add(v);
        seen[v] = true;
      }
    }
    return component;
  }

  private long calculateScore(int left, int right, boolean isCycle) {
    Deque<Long> window = new ArrayDeque<>();
    window.offerLast((long) right);
    window.offerLast((long) right);
    long score = 0;
    for (int value = right - 1; value >= left; --value) {
      final long windowValue = window.pollFirst();
      score += windowValue * value;
      window.offerLast((long) value);
    }
    return score + window.peekFirst() * window.peekLast() * (isCycle ? 1 : 0);
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

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

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.