VISUALGO//PROBLEMS
maximum twin sum of a linked list · linked listmedium
LeetCode #2130
list
5
→
4
→
2
→
1
sum
·
max
·
ELEMENTS
head
Python
def pairSum(head: ListNode | None) -> int:
    # 1. find the start of the second half
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    # 2. reverse the second half
    prev = None
    while slow:
        slow.next, prev, slow = prev, slow, slow.next

    # 3. walk both halves together; each pair is a node and its twin
    best = 0
    first, second = head, prev
    while second:
        best = max(best, first.val + second.val)
        first = first.next
        second = second.next

    return best