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 node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 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.
graph LR
E(5):::blue --> D(4):::red --> B(2):::red --> A(1):::blue
classDef red fill:#FF0000,stroke:#000,stroke-width:1px,color:#fff;
classDef blue fill:#87CEEB,stroke:#333,stroke-width:2px;
1
2
3
4
5
6
7
Input: head =[5,4,2,1]Output: 6Explanation:
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 is6.
graph LR
D(4):::blue --> B1(2):::red --> B2(2):::red --> C(3):::blue
classDef red fill:#FF0000,stroke:#000,stroke-width:1px,color:#fff;
classDef blue fill:#87CEEB,stroke:#333,stroke-width:2px;
1
2
3
4
5
6
7
Input: head =[4,2,2,3]Output: 7Explanation:
The nodes with twins present inthis linked list are:- Node 0is the twin of node 3 having a twin sum of 4+3=7.- Node 1is the twin of node 2 having a twin sum of 2+2=4.Thus, the maximum twin sum of the linked list ismax(7,4)=7.
The twin sum pairs the first half of the list with the second half in reverse order. By finding the middle, reversing the second half, and pairing nodes, we can efficiently compute all twin sums and track the maximum.
classSolution {
funpairSum(head: ListNode?): Int {
var slow = head
var fast = head
while (fast !=null&& fast.next !=null) {
slow = slow?.next
fast = fast.next.next
}
var prev: ListNode? = nullvar cur = slow
while (cur !=null) {
val next = cur.next
cur.next = prev
prev = cur
cur = next
}
var ans = 0var p1 = head
var p2 = prev
while (p2 !=null) {
ans = maxOf(ans, p1!!.`val` + p2.`val`)
p1 = p1.next
p2 = p2.next
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
defpair_sum(head: 'ListNode') -> int:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
prev, cur =None, slow
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
ans =0 p1, p2 = head, prev
while p2:
ans = max(ans, p1.val + p2.val)
p1 = p1.next
p2 = p2.next
return ans