Maximum Score of a Node Sequence - Problem
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] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.
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.
Input & Output
Example 1 — Basic Valid Sequence
$
Input:
scores = [5,2,9,6,7], edges = [[0,1],[1,2],[2,3],[0,2],[3,4]]
›
Output:
24
💡 Note:
The optimal 4-node sequence is 0→2→3→4 with scores 5+9+6+7=24. All consecutive nodes are connected by edges.
Example 2 — No Valid Sequence
$
Input:
scores = [9,20,6,4,11,12], edges = [[0,3],[5,1],[2,3],[5,2]]
›
Output:
-1
💡 Note:
No valid 4-node sequence exists. The graph doesn't have enough connected nodes to form a path of length 4.
Example 3 — Multiple Valid Paths
$
Input:
scores = [1,2,3,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3]]
›
Output:
10
💡 Note:
Multiple valid paths exist like 0→1→2→3 (score=10) and 0→2→1→3 (score=10). Return the maximum score.
Constraints
- n == scores.length
- 4 ≤ n ≤ 5 × 104
- 1 ≤ scores[i] ≤ 108
- 0 ≤ edges.length ≤ 5 × 104
- edges[i].length == 2
- 0 ≤ ai, bi ≤ n - 1
- ai ≠ bi
- There are no duplicate edges.
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Graph with node scores and edges
2
Find Valid Paths
Enumerate all valid 4-node sequences
3
Calculate Scores
Sum scores for each valid path
4
Return Maximum
Return highest score found
Key Takeaway
🎯 Key Insight: Focus on middle edges to efficiently enumerate valid 4-node paths instead of checking all combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code