#2242
Maximum Score of a Node Sequence
HardArrayGraph TheorySortingEnumerationGraph TraversalSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n^4) | O(n + e log e) |
| Space | O(n) | O(n + e) |
💡
Intuition
Time O(n + e log e)Space O(n + e)
The optimal solution leverages the idea of fixing two nodes connected by an edge and searching for the best two additional nodes to maximize the score. This reduces the number of checks significantly compared to the brute force method.
⚙️
Algorithm
4 steps- 1Step 1: Create an adjacency list from the edges to represent the graph.
- 2Step 2: For each edge (u, v), consider u and v as the middle nodes of the sequence.
- 3Step 3: For each of the two middle nodes, find the top two nodes connected to them that maximize the score.
- 4Step 4: Calculate the score for the sequence formed by u, v, and the two best nodes found, and keep track of the maximum score.
solution.py23 lines
1# Full working Python code
2from collections import defaultdict
3
4def maxScore(scores, edges):
5 n = len(scores)
6 graph = defaultdict(list)
7 for u, v in edges:
8 graph[u].append(v)
9 graph[v].append(u)
10 max_score = -1
11 for u, v in edges:
12 candidates = []
13 for neighbor in graph[u]:
14 if neighbor != v:
15 candidates.append(scores[neighbor])
16 for neighbor in graph[v]:
17 if neighbor != u:
18 candidates.append(scores[neighbor])
19 candidates.sort(reverse=True)
20 if len(candidates) >= 2:
21 score = scores[u] + scores[v] + candidates[0] + candidates[1]
22 max_score = max(max_score, score)
23 return max_scoreℹ
Complexity note: The time complexity is O(n + e log e) due to building the adjacency list and sorting the candidates. The space complexity is O(n + e) for storing the graph and candidates.
- 1Fixing two nodes connected by an edge significantly reduces the search space.
- 2Using an adjacency list allows efficient access to connected nodes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.