[/dsa/leetcode]

2130 - Maximum Twin Sum of a Linked List

Friday, 18 September 2026

<medium> [problem]

Twins are the pairs a palindrome check compares, so the machinery from 234 works unchanged - find the middle, reverse the back half, and take a max instead of an equality test.

{linked list}{two pointers}

Problem

In a linked list of size n, where n is even, the ith node (0-indexed) is known as the twin of the (n-1-i)th node, for 0 <= i <= n/2 - 1.

The twin sum is the sum of a node and its twin. Return the maximum twin sum of the list.

Input: head = [5,4,2,1]
Output: 6
Explanation: twins are (5,1) and (4,2), sums 6 and 6

Input: head = [4,2,2,3]
Output: 7
Explanation: twins are (4,3) and (2,2), sums 7 and 4

Input: head = [1,100000]
Output: 100001

Constraints:

  • The number of nodes is an even integer in the range [2, 10^5]
  • 1 <= Node.val <= 10^5

Approach

5 -> 4 -> 2 -> 1            slow stops on index 2

5 -> 4    2 <- 1            reverse from slow; prev is the new head
|    |    |    |
l ------> <------ r         (5,1) then (4,2)
class Solution {
public:
    int pairSum(ListNode* head) {
        ListNode* slow = head, *fast = head;
        while(fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* prev = nullptr;
        ListNode* curr = slow;
        while(curr) {
            ListNode* next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        ListNode* l = head, *r = prev;
        int maxi = INT_MIN;
        while(r) {
            maxi = max(maxi, l->val + r->val);
            l = l->next;
            r = r->next;
        }
        return maxi;
    }
};
  • time: O(n) - one pass to the middle, one to reverse, one to fold
  • space: O(1) - a few pointers, nodes relinked in place
quantinium © 2026