Maximum Twin Sum of a Linked List - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
head = [5,4,2,1]
›
Output:
6
💡 Note:
Nodes (0,3) are twins with sum 5+1=6. Nodes (1,2) are twins with sum 4+2=6. Maximum is 6.
Example 2 — Different Values
$
Input:
head = [4,2,2,3]
›
Output:
7
💡 Note:
Nodes (0,3) are twins with sum 4+3=7. Nodes (1,2) are twins with sum 2+2=4. Maximum is 7.
Example 3 — Minimum Size
$
Input:
head = [1,100000]
›
Output:
100001
💡 Note:
Only one twin pair (0,1) with sum 1+100000=100001.
Constraints
- The number of nodes in the list is in the range [2, 105].
- 1 ≤ Node.val ≤ 105
- The number of nodes in the list is even.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Linked list [5,4,2,1] with even length
2
Twin Pairing
Node i pairs with node (n-1-i)
3
Output
Maximum twin sum is 6
Key Takeaway
🎯 Key Insight: Twin nodes are at mirrored positions - convert to array for easy access or use stack/reversal for space optimization
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code