Maximum Score of a Node Sequence Problem
Description
LeetCode Problem 2242.
There is an undirected graph with n nodes, numbered from 0 to n - 1.
You are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [a_i, b_i] denotes that there exists an undirected edge connecting nodes a_i and b_i.
A node sequence is valid if it meets the following conditions:
- There is an edge connecting every pair of adjacent nodes in the sequence.
- No node appears more than once in the sequence.
The score of a node sequence is defined as the sum of the scores of the nodes in the sequence.
Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1.
Example 1:

Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
Output: 24
Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3].
The score of the node sequence is 5 + 2 + 9 + 8 = 24.
It can be shown that no other node sequence has a score of more than 24.
Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.
The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.
Example 2:

Input: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]
Output: -1
Explanation: The figure above shows the graph.
There are no valid node sequences of length 4, so we return -1.
Constraints:
n == scores.length4 <= n <= 5 * 10^41 <= scores[i] <= 10^80 <= edges.length <= 5 * 10^4edges[i].length == 20 <= a_i, b_i <= n - 1a_i != b_i- There are no duplicate edges.
Solution
Approach: Enumerate the Middle Edge + Top 3 Neighbors
A valid sequence is a path a - b - c - d, so its middle is an edge (b, c), and a and d are neighbors of c and b respectively.
For each node keep only its 3 neighbors with the largest scores. That is enough: of the neighbors of b, at most two are excluded (c and d), so one of the top three is always usable.
Then for every edge (a, b) try each kept neighbor c of a and each kept neighbor d of b, and accept the four nodes if they are all different. The best sum is the answer, or -1 if no sequence exists.
Complexity: O(n + m log m) time (sorting neighbor lists) and O(n + m) space, with m the number of edges.
from collections import defaultdict
from heapq import nlargest
class Solution:
def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
for k in g.keys():
g[k] = nlargest(3, g[k], key=lambda x: scores[x])
ans = -1
for a, b in edges:
for c in g[a]:
for d in g[b]:
if b != c != d != a:
t = scores[a] + scores[b] + scores[c] + scores[d]
ans = max(ans, t)
return ans