Maximum Twin Sum of a Linked List - Problem
In a linked list of even length n, imagine pairing up nodes like dance partners! The ith node (0-indexed) pairs with the (n-1-i)th node, creating beautiful symmetrical pairs called twins.
For example, in a linked list with 4 nodes:
- Node 0 twins with Node 3
- Node 1 twins with Node 2
The twin sum is simply the sum of a node's value and its twin's value. Your mission is to find the maximum twin sum among all possible twin pairs in the linked list.
Goal: Given the head of a linked list with even length, return the maximum twin sum.
Input & Output
example_1.py โ Basic Case
$
Input:
head = [5,4,2,1]
โบ
Output:
6
๐ก Note:
The linked list has 4 nodes. Twin pairs are: (node 0, node 3) = (5,1) with sum 6, and (node 1, node 2) = (4,2) with sum 6. Maximum twin sum is 6.
example_2.py โ Larger Values
$
Input:
head = [4,2,2,3]
โบ
Output:
7
๐ก Note:
Twin pairs are: (node 0, node 3) = (4,3) with sum 7, and (node 1, node 2) = (2,2) with sum 4. Maximum twin sum is 7.
example_3.py โ Minimum Case
$
Input:
head = [1,100000]
โบ
Output:
100001
๐ก Note:
With only 2 nodes, there's one twin pair: (node 0, node 1) = (1,100000) with sum 100001.
Constraints
- The number of nodes in the list is in the range [2, 105]
- The number of nodes is even
- 1 โค Node.val โค 105
Visualization
Tap to expand
Understanding the Visualization
1
Line Up Dancers
All dancers stand in a single file line, each with their skill level
2
Form Twin Pairs
First dancer pairs with last, second with second-to-last, creating symmetrical pairs
3
Calculate Harmony
Each pair's harmony score is the sum of both dancers' skill levels
4
Find Best Pair
The pair with the highest harmony score wins the competition
Key Takeaway
๐ฏ Key Insight: The symmetrical pairing pattern (i with n-1-i) allows us to use data structures like stacks or arrays to efficiently match twins and find the maximum harmony score in linear time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code