KatInterview

Best Hub-and-Spokes Value Sum with a Spoke Limit

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphgreedysorting

Last updated

Choose a hub node and up to k adjacent nodes to maximize the total node value, which tests per-node greedy selection over adjacency lists.

You are given an undirected graph where every node carries an integer value, along with an integer k. Build a "hub-and-spokes" selection by picking one hub node and then some of its direct neighbors as spokes. Your job is to find the largest possible total value of such a selection.

Rules for a valid selection

  • Exactly one node is the hub.
  • Zero or more spokes may be chosen, but at most k of them.
  • Every spoke must be a distinct node that shares an edge with the hub.
  • A hub with no spokes is a valid selection.
  • Each chosen node (the hub and every spoke) contributes its value exactly once to the total.
  • Edges between two spokes are irrelevant. You only need the hub-to-spoke edges, and any extra edges among chosen nodes are simply ignored.

Task

Implement max_hub_spoke_sum(num_nodes, edge_from, edge_to, values, k).

  • num_nodes is the number of nodes, labeled 0 to num_nodes - 1.
  • edge_from and edge_to have the same length. The i-th edge connects edge_from[i] and edge_to[i].
  • values[i] is the value of node i.
  • k is the maximum number of spokes allowed.

Return a single integer: the maximum total value over all valid selections. Since a selection always contains at least the hub, the result is never an empty sum. If every value is negative, the answer is the best single node value, not 0.

Constraints

  • 2 <= num_nodes <= 100000
  • 1 <= len(edge_from) = len(edge_to) <= 100000
  • All edge endpoints are valid node labels.
  • No self-loops, and no pair of nodes is joined by more than one edge.
  • len(values) = num_nodes and -1000 <= values[i] <= 1000
  • 0 <= k <= 100000
  • The graph may be disconnected.

Examples

Example 1

Input: max_hub_spoke_sum(4, [0, 0, 0], [1, 2, 3], [5, 4, -2, 3], 2)

Output: 12

Example 2

Input: max_hub_spoke_sum(2, [0], [1], [-4, -1], 1)

Output: -1

Hints

Hint 1

Every valid selection has exactly one hub. What happens if you fix the hub and ask for the best set of spokes only for that hub?

Hint 2

Once the hub is fixed, the spokes are independent of each other: each neighbor just adds its own value. Which neighbors should you never take, given that fewer than k spokes is allowed?

Hint 3

For each hub, sum the k largest strictly positive neighbor values and add the hub's own value. Take the maximum over all hubs, and do not start your running best at 0 because the all-negative case must return a negative number.