LeetCode 题解工作台
链表最大孪生和
在一个大小为 n 且 n 为 偶数 的链表中,对于 0 的 i ,第 i 个节点(下标从 0 开始)的孪生节点为第 (n-1-i) 个节点 。 比方说, n = 4 那么节点 0 是节点 3 的孪生节点,节点 1 是节点 2 的孪生节点。这是长度为 n = 4 的链表中所有的孪生节点。 孪生和 定义…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们可以将链表中的节点值依次存入数组中,然后使用双指针分别指向数组的开头和结尾,计算每对孪生节点的孪生和,取最大值即为答案。 时间复杂度 ,空间复杂度 。其中 是链表的节点数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
在一个大小为 n 且 n 为 偶数 的链表中,对于 0 <= i <= (n / 2) - 1 的 i ,第 i 个节点(下标从 0 开始)的孪生节点为第 (n-1-i) 个节点 。
- 比方说,
n = 4那么节点0是节点3的孪生节点,节点1是节点2的孪生节点。这是长度为n = 4的链表中所有的孪生节点。
孪生和 定义为一个节点和它孪生节点两者值之和。
给你一个长度为偶数的链表的头节点 head ,请你返回链表的 最大孪生和 。
示例 1:

输入:head = [5,4,2,1] 输出:6 解释: 节点 0 和节点 1 分别是节点 3 和 2 的孪生节点。孪生和都为 6 。 链表中没有其他孪生节点。 所以,链表的最大孪生和是 6 。
示例 2:

输入:head = [4,2,2,3] 输出:7 解释: 链表中的孪生节点为: - 节点 0 是节点 3 的孪生节点,孪生和为 4 + 3 = 7 。 - 节点 1 是节点 2 的孪生节点,孪生和为 2 + 2 = 4 。 所以,最大孪生和为 max(7, 4) = 7 。
示例 3:

输入:head = [1,100000] 输出:100001 解释: 链表中只有一对孪生节点,孪生和为 1 + 100000 = 100001 。
提示:
- 链表的节点数目是
[2, 105]中的 偶数 。 1 <= Node.val <= 105
解题思路
方法一:模拟
我们可以将链表中的节点值依次存入数组中,然后使用双指针分别指向数组的开头和结尾,计算每对孪生节点的孪生和,取最大值即为答案。
时间复杂度 ,空间复杂度 。其中 是链表的节点数。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
s = []
while head:
s.append(head.val)
head = head.next
n = len(s)
return max(s[i] + s[-(i + 1)] for i in range(n >> 1))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for traversing the list and computing twin sums. Space complexity is O(1) for in-place reversal or O(n/2) for the stack method. Each node is processed exactly once. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about how to pair nodes efficiently without extra full-list storage.
- question_mark
Look for discussions on reversing part of the list or using a stack to match twins.
- question_mark
Probe if candidate can handle edge cases like minimal list size and large values.
常见陷阱
外企场景- error
Failing to correctly identify twin indices and summing wrong pairs.
- error
Modifying the list incorrectly without restoring its structure if needed.
- error
Using unnecessary extra space or traversing nodes multiple times.
进阶变体
外企场景- arrow_right_alt
Find the minimum twin sum instead of the maximum in the linked list.
- arrow_right_alt
Handle odd-length lists by ignoring the middle node or pairing differently.
- arrow_right_alt
Compute twin sums while returning a list of all twin pairs instead of just the maximum.