In a linked list of size n
, where n
is even, the ith
node (0-indexed) of the linked list is known as the twin of the (n-1-i)th
node, if 0 <= i <= (n / 2) - 1
.
- For example, if
n = 4
, then node0
is the twin of node3
, and node1
is the twin of node2
. These are the only nodes with twins forn = 4
.
The twin sum is defined as the sum of a node and its twin.
Given the head
of a linked list with even length, return the maximum twin sum of the linked list.
Example 1:
Input: head = [5,4,2,1] Output: 6 Explanation: Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6. There are no other nodes with twins in the linked list. Thus, the maximum twin sum of the linked list is 6.
Example 2:
Input: head = [4,2,2,3] Output: 7 Explanation: The nodes with twins present in this linked list are: - Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. - Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. Thus, the maximum twin sum of the linked list is max(7, 4) = 7.
Example 3:
Input: head = [1,100000] Output: 100001 Explanation: There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
Constraints:
- The number of nodes in the list is an even integer in the range
[2, 105]
. 1 <= Node.val <= 105
题目说一个链表含有n个节点,n一定为偶数,把第i个节点(链表头为第0个节点)与 第(n/2) +i个节点称为双胞胎节点,两个双胞胎节点的和就称为双胞胎和。要求找出链表中最大的双胞胎和。
根据题意,其实就是把一个具有n个(n为偶数)的链表从正中间把链表分成两部分,即为两个节点个数相等的子链表,那么所有的双胞胎节点就是,第一个子链表从头到尾与第二个链表从尾到头一一对应构成一对对双胞胎节点,从这些匹配的双胞胎节点中找出和最大的那一对。
综上所述,这题的代码实现应该分为两个部分:
1)把链表中间分成两个长度相同的子链表,最快的方法就是链表Linked List系列里最常用的快慢指针法。用两个指针指向链表头,慢指针每次移动一步而快指针每次移动两步,当快指针走到链表尾时,慢指针刚好走一半即把整个链表分成了两个部分,慢指针所指的节点就是第二部分的开头节点。
2)求所有双胞胎节点和,找出最大值。第一步已经把链表分成了两部分,根据题目对双胞胎节点的定义,双胞胎节点就是:第一部分的最后一个节点与第二部分的第一个节点,第一部分的倒数第二个节点与第二部分的第二个节点,......, 第一部分的第一个节点与第二部分的最后一个节点。很显然这里可以一个堆栈来实现,把第一部分的节点按从头到尾的顺序放入堆栈中,再依次取出与第二部分的节点从头到尾的顺序一一匹配构成双胞胎节点。
class Solution:
def pairSum(self, head: Optional[ListNode])->int:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
res = 0
st = []
while head != slow:
st.append(head)
head = head.next
while st:
res = max(res, st.pop().val + slow.val)
slow = slow.next
return res