Skip to main content
LeetCode 2285, Medium. Topics: Greedy, Graph Theory, Sorting, Heap (Priority Queue). View on LeetCode. Generate this problem as a practice environment: tested reference solution, 19 parametrized pytest cases, and a playground notebook:

Problem

You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1. You are also given a 2D integer array roads where roads[i] = [a<sub>i</sub>, b<sub>i</sub>] denotes that there exists a bidirectional road connecting cities a<sub>i</sub> and b<sub>i</sub>. You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects. Return the maximum total importance of all roads possible after assigning the values optimally.

Examples

Example 1
Example 2

Constraints

  • 2 <= n <= 5 * 10<sup>4</sup>
  • 1 <= roads.length <= 5 * 10<sup>4</sup>
  • roads[i].length == 2
  • 0 <= a<sub>i</sub>, b<sub>i</sub> <= n - 1
  • a<sub>i</sub> != b<sub>i</sub>
  • There are no duplicate roads.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026