Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2242: Maximum Score of a Node Sequence

In this guide, we solve Leetcode #2242 Maximum Score of a Node Sequence in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Graph, Array, Enumeration, Sorting

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

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.

Python Solution

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

Complexity

The time complexity is O(V+E). The space complexity is O(V).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy