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
๐Ÿ•บ Twin Pairing Dance Competition ๐Ÿ’ƒDancers in Line:5Alice4Bob2Carol1DaveTwin Pairs Formation:54Pair 1: 4 + 2 = 621Pair 2: 2 + 1 = 3๐Ÿ† Competition ResultsAlice & Bob: 5 + 4 = 9Carol & Dave: 2 + 1 = 3Winner: Harmony Score = 9Twin Pairing Rule: Position i pairs with position (n-1-i)Alice (pos 0) โ†” Dave (pos 3), Bob (pos 1) โ†” Carol (pos 2)
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!
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
58.9K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen