Maximum-Sum Star with at Most K Arms
C3 AISoftware Engineer · Online AssessmentLast updated
Find the maximum node-value sum of a graph star with at most k arms, allowing a center alone and avoiding harmful negative-value leaves.
Given a simple undirected graph with an integer value on each node and an integer k, return the largest node-value sum of any nonempty star subgraph with at most k arms.
A star has one center and zero or more distinct neighbors selected as leaves. Each selected leaf must be joined to the center by a graph edge. A center alone is a valid star. Count each selected node's value once. The chosen star is a subgraph: any edges between selected leaves need not be included.
Function and Inputs
Complete bestSumKStar(g_nodes, g_from, g_to, values, k):
g_nodesis the number of nodes, labeled0throughg_nodes - 1.g_fromandg_toare equally sized arrays. Edgeijoinsg_from[i]andg_to[i].values[i]is the integer value of nodei.kis the maximum number of arms in the star.
Return one integer: the maximum sum among all allowed stars.
Constraints
2 <= g_nodes <= 100000and1 <= g_edges <= 100000, whereg_edgesis the length of each edge array.- Every edge endpoint is a valid node label. The graph has no self-loops and at most one edge between a pair of nodes.
valueshas lengthg_nodes, and-1000 <= values[i] <= 1000.0 <= k <= 100000. The graph need not be connected.
Example 1
g_nodes = 4
g_from = [0, 0, 0]
g_to = [1, 2, 3]
values = [5, 4, -2, 3]
k = 2
answer = 12
The star centered at node 0 with leaves 1 and 3 has sum 5 + 4 + 3 = 12.
Example 2
g_nodes = 2
g_from = [0]
g_to = [1]
values = [-4, -1]
k = 1
answer = -1
The valid star containing only node 1 has sum -1.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.