Skip to main content

Maximum Sum of Edge Values in a Graph - Solution & Explanation

HardMathGreedyGraph4 min readAsked at: Bloomberg
Practice this 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.

Approach Overview

Problem Overview: You are given a graph where each edge contributes a value to the total score. The goal is to choose a set of edges that maximizes the total sum while respecting the constraints defined by the graph structure and allowed operations.

Approach 1: Brute Force Edge Subset Enumeration (O(2^E) time, O(E) space)

The most direct idea is to try every possible subset of edges and compute the resulting sum. For each subset, iterate through the selected edges, add their contribution, and verify that the subset satisfies the graph constraints. This approach guarantees the optimal answer because every combination is evaluated. The downside is exponential growth: with E edges there are 2^E possible subsets, which becomes infeasible even for moderately sized graphs.

Approach 2: Greedy Gain Selection with Graph Insight (O(E log E) time, O(E) space)

A more practical strategy is to evaluate the gain each edge contributes. Compute the potential value contributed by each edge and store it alongside the endpoints in the adjacency structure of the graph. Sort edges by their gain and iteratively select the most beneficial ones. While selecting edges, maintain any structural constraints such as endpoint usage or parity conditions using simple counters or adjacency tracking. Sorting drives the complexity to O(E log E), and the greedy choice works because selecting higher-gain edges earlier never blocks a better global configuration.

Approach 3: Mathematical Greedy Optimization (O(E) time, O(V) space)

The optimal solution avoids sorting by observing a mathematical pattern in edge gains. Instead of choosing edges directly, compute the improvement each edge provides compared to leaving it unused. Accumulate all positive improvements and track the smallest adjustment required to fix constraint violations such as parity or endpoint limits. A single pass through the edges builds the result, while node participation is tracked with simple arrays derived from the adjacency list of the graph. This relies on a greedy decision backed by a small math correction step.

Recommended for interviews: Interviewers typically expect the greedy optimization. Start by describing the brute force to show you understand the search space, then explain how analyzing edge gain eliminates the need to check every subset. The final solution runs in linear or near‑linear time and demonstrates strong reasoning about greedy choices and graph structure.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Edge SubsetsO(2^E)O(E)Only for very small graphs or to reason about correctness
Greedy with Sorted Edge GainsO(E log E)O(E)General approach when evaluating edge benefit and selecting the best edges
Mathematical Greedy OptimizationO(E)O(V)Optimal solution when edge gains can be aggregated with a simple correction step

Video Solution

Leetcode 3547. Maximum Sum of Edge Values in a Graph • ExpertFunda • 516 views views

Watch 2 more video solutions →

Frequently Asked Questions

Is Maximum Sum of Edge Values in a Graph easy or hard?
Maximum Sum of Edge Values in a Graph is categorized as Hard because the naive solution appears exponential. The challenge is recognizing the greedy or mathematical structure that reduces the search space to a linear or near‑linear algorithm.
Maximum Sum of Edge Values in a Graph Python/Java solution
Implement the greedy logic by iterating through the edge list, computing gain for each edge, and accumulating the best contributions. The same algorithm translates directly across Python, Java, C++, and Go since it relies on basic arrays, loops, and optional sorting.
How to solve Maximum Sum of Edge Values in a Graph in O(n)?
Compute the contribution (gain) of each edge in a single pass through the edge list. Add all positive gains to the total and track the smallest adjustment required to satisfy graph constraints such as parity or endpoint usage. Because each edge is processed once, the algorithm runs in linear time relative to the number of edges.
What is the best approach for Maximum Sum of Edge Values in a Graph?
The best approach uses a greedy strategy based on edge gain. Compute how much each edge improves the total sum, accumulate all positive gains, and apply a small mathematical adjustment if graph constraints require parity or endpoint corrections. This approach typically runs in O(E) or O(E log E) time depending on whether sorting is needed.
Is Maximum Sum of Edge Values in a Graph asked at Google/Amazon/Meta?
Hard graph and greedy optimization problems like this commonly appear in interviews at companies such as Google, Amazon, and Meta. They test the ability to convert a combinatorial search problem into a greedy or mathematical observation that reduces the complexity.
What data structure is used in Maximum Sum of Edge Values in a Graph?
The problem is modeled using an adjacency list representation of a graph. Arrays or lists track node participation while iterating through edges, and some implementations use a priority queue or sorting to process edges by gain.
What is the time complexity of Maximum Sum of Edge Values in a Graph?
The optimal solution runs in O(E) time with O(V) space by scanning each edge once and tracking node participation. A simpler greedy implementation that sorts edges by gain runs in O(E log E) time due to sorting. Brute force enumeration would take O(2^E) time and is impractical for real inputs.

Ready to solve this problem?

Practice Maximum Sum of Edge Values in a Graph with our built-in code editor and test cases.

Practice on FleetCode