这是 LeetCode 2242. 节点序列的最大得分 的 TypeScript 实现。

---

核心思路回顾

1. 建图:用邻接表存储无向图
2. 剪枝:每个节点只保留分数最高的 3 个邻居(因为最坏情况下,互为最大邻居 + 重复节点,3个足够覆盖最优解)
3. 枚举中间边:遍历每条边 `(b, c)`,枚举 `b` 的邻居 `a` 和 `c` 的邻居 `d`
4. 去重:确保 `a, b, c, d` 互不相同

---

TypeScript 代码

```typescript
function maximumScore(scores: number[], edges: number[][]): number {
    const n = scores.length;
    
    // 建图
    const graph: number[][] = Array.from({ length: n }, () => []);
    for (const [u, v] of edges) {
        graph[u].push(v);
        graph[v].push(u);
    }
    
    // 每个节点只保留分数最高的 3 个邻居
    for (let i = 0; i < n; i++) {
        graph[i].sort((a, b) => scores[b] - scores[a]);
        if (graph[i].length > 3) {
            graph[i] = graph[i].slice(0, 3);
        }
    }
    
    let ans = -1;
    
    // 枚举每条边作为中间边 (b, c)
    for (const [b, c] of edges) {
        for (const a of graph[b]) {
            for (const d of graph[c]) {
                // 四个节点必须互不相同
                if (a !== c && a !== d && b !== d) {
                    const score = scores[a] + scores[b] + scores[c] + scores[d];
                    ans = Math.max(ans, score);
                }
            }
        }
    }
    
    return ans;
}
```

---

复杂度分析

项目    复杂度    
时间    `O(E)` — 建图 `O(E)`,剪枝排序 `O(n log n)`,枚举 `O(E × 3 × 3) = O(E)`    
空间    `O(n)` — 邻接表存储    

---

关键点说明

要点    说明    
为什么只保留 3 个邻居    最坏情况:`b` 最大邻居是 `c`,`c` 最大邻居是 `b`,且 `a == d`,需要第 2、3 大的邻居    
枚举中间边 `(b, c)`    序列 `a - b - c - d`,`(b, c)` 是中间边,大幅降低搜索空间    
去重条件    `a !== c && a !== d && b !== d` 确保 4 个节点互不相同    
无解返回 `-1`    如果没有任何合法序列,`ans` 保持初始值 `-1`    

> 参考:[mocowcow 题解](https://mocowcow.github.io/leetcode-2242-maximum-score-of-a-node-sequence/)

 

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐