Approach
Breadth-first search
For Maximum Sum of Edge Values in a Graph, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 56 lines of Python from the credited upstream file 3547.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def maxScore(self, n: int, edges: list[list[int]]) -> int:3 ans = 04 graph = [[] for _ in range(n)]5 cycleSizes = [] 6 pathSizes = [] 7 seen = set()8 9 for u, v in edges:10 graph[u].append(v)11 graph[v].append(u)12 13 for i in range(n):14 if i in seen:15 continue16 component = self._getComponent(graph, i, seen)17 if all(len(graph[u]) == 2 for u in component):18 cycleSizes.append(len(component))19 elif len(component) > 1:20 pathSizes.append(len(component))21 22 for cycleSize in cycleSizes:23 ans += self._calculateScore(n - cycleSize + 1, n, True)24 n -= cycleSize25 26 for pathSize in sorted(pathSizes, reverse=True):27 ans += self._calculateScore(n - pathSize + 1, n, False)28 n -= pathSize29 30 return ans31 32 def _getComponent(33 self,34 graph: list[list[int]],35 start: int,36 seen: set[int],37 ) -> list[int]:38 component = [start]39 seen.add(start)40 for u in component:41 for v in graph[u]:42 if v in seen:43 continue44 component.append(v)45 seen.add(v)46 return component47 48 def _calculateScore(self, left: int, right: int, isCycle: bool) -> int:49 window = collections.deque([right, right])50 score = 051 for value in range(right - 1, left - 1, -1):52 windowValue = window.popleft()53 score += windowValue * value54 window.append(value)55 return score + window[0] * window[1] * isCycle56