Problem Description
Given an undirected graph with n nodes (numbered from 0 to n–1), each node has an associated score provided in the array scores. A list of edges specifies the connections between nodes. A valid node sequence of length 4 is one in which every pair of adjacent nodes is connected by an edge and no node appears more than once. The task is to find the valid sequence with the maximum total score (i.e. the sum of scores of nodes in the sequence). If no such sequence exists, return –1.
Key Insights
- Since the sequence must be of length 4, a natural candidate structure is: a, b, c, d where b and c are connected by an edge and a is connected to b while d is connected to c.
- For each node, keep track of the top (up to) three neighbors (based on their scores) that can be candidates to form the sequence endpoints.
- Iterate over each edge and treat it as the middle edge (between b and c). Then, try to attach the best candidate neighbors from b (for a) and from c (for d), ensuring all four nodes are distinct.
- The candidate lists for each node are maintained in descending order of scores to quickly obtain high-scoring endpoints.
- Carefully check for distinctness among the four nodes when combining candidate endpoints with the central edge.
Space and Time Complexity
Time Complexity: O(m) where m is the number of edges, since for each edge we only try a constant number of candidate extensions. Space Complexity: O(n + m) for the graph representation and candidate lists.
Solution
We precompute for each node a sorted list (by score) of up to three neighboring nodes. Then, for every edge (u, v) in the graph, we consider it as the middle edge of a potential sequence. For node u, choose a candidate neighbor a (from its candidate list) that is not v. Similarly, for node v, choose a candidate neighbor d (from its candidate list) that is not u and not equal to a. Compute the total score as scores[a] + scores[u] + scores[v] + scores[d]. Update the maximum score encountered. Edge cases such as missing candidates or duplicate nodes in the sequence are handled by these checks.