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
Signature
...Complexity
- Time:
O(n) - Space:
O(1)
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
=
=
# n = head
= =
# prev = None
# print(n.val)
# n = n.next
# prev = slow
=
=
# print(prev.val)
# print(slow.val)
=
= None
# print(curr.val, curr.next)
=
=
=
=
# print(prev.val)
# print(head.val)
=
=
= 0
=
=
=
return