Maximum Twin Sum of a Linked List

Pair the i-th node with the (n-1-i)-th node; return the max twin sum using the middle-reverse trick.

Medium
Time O(n) Space O(1)
LeetCode
4 min read
fast-slow linked-list

Problem#

A linked list has even length n. For each i ∈ [0, n/2), the twin of node i is node n - 1 - i. Return the maximum twin sum.

Examples#

  • [5,4,2,1]6 (5+1 = 6, 4+2 = 6)
  • [4,2,2,3]7 (4+3, 2+2)

Constraints#

  • Even length in [2, 10^5].

Approach#

Same primitives as palindrome-linked-list: find middle, reverse second half, walk both halves in lockstep summing pairs.

Solution#

Maximum Twin Sum
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;
while (slow) {
ListNode* nxt = slow->next;
slow->next = prev;
prev = slow;
slow = nxt;
}
int best = 0;
ListNode *a = head, *b = prev;
while (b) {
best = max(best, a->val + b->val);
a = a->next; b = b->next;
}
return best;
}
};

Editorial#

Even length means the fast/slow split is exact — no middle special case. After reversing the second half, the linked-list version of “pair i with n-1-i” is just “advance two pointers from each end of the new structure”. The pattern compose cleanly.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.