Maximum Twin Sum of a Linked List
Description
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.
Example 1:
Input: head = [5, 4, 2, 1]
Output: 6
Explanation: Nodes 0 and 1 are twins of nodes 3 and 2 respectively. Twin sums are: 5 + 1 = 6, 4 + 2 = 6. The maximum twin sum is 6.
Example 2:
Input: head = [4, 2, 2, 3]
Output: 7
Explanation: Nodes 0 and 1 are twins of nodes 3 and 2 respectively. Twin sums are: 4 + 3 = 7, 2 + 2 = 4. The maximum twin sum is 7.
Example 3:
Input: head = [1, 100000]
Output: 100001
Explanation: Only one pair of twins (node 0 and node 1). Twin sum is 1 + 100000 = 100001.
Constraints
The number of nodes in the list is an even integer in the range [2, 10^5]1 <= Node.val <= 10^5
Complexity
Show Complexity
- Time:
O(n) - Space:
O(1)
Hints
Show Hints
- Pattern
- Two pointers with linked list reversal
- Approach
- Use slow/fast pointers to find middle, reverse second half, then sum pairs from start and reversed second half
- Complexity
- Reverse second half, then compare first and reversed second half
Solutions
Show PY Solution
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def solution(head: Optional[ListNode]) -> int:
# n = head
slow = fast = head
# prev = None
while fast and fast.next:
# print(n.val)
# n = n.next
# prev = slow
slow = slow.next
fast = fast.next.next
# print(prev.val)
# print(slow.val)
curr = slow
prev = None
while curr:
# print(curr.val, curr.next)
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
# print(prev.val)
# print(head.val)
p1 = head
p2 = prev
ans = 0
while p2:
ans = max(ans, p1.val + p2.val)
p1 = p1.next
p2 = p2.next
return ans