SDE & MLE Prep

2130. Maximum Twin Sum of a Linked List

Problem

In a linked list of even length n, node i (0-based) and node n − 1 − i are twins. Return the maximum twin sum.

Example: 5→4→2→1 → 6; 4→2→2→3 → 7

Constraints: n ≤ 10⁵.

Same toolkit as Palindrome Linked List: find the middle with fast/slow, reverse the second half, then walk both halves together summing twins.

Complexity: O(n) time, O(1) space.

class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        prev = None                                  # reverse the second half
        while slow:
            slow.next, prev, slow = prev, slow, slow.next
        best = 0
        while prev:
            best = max(best, head.val + prev.val)
            head, prev = head.next, prev.next
        return best