Maximum Twin Sum of a Linked List — Split and Reverse
Advertisement
Problem 236 · Maximum Twin Sum of a Linked List
Difficulty: Medium · Pattern: Fast/Slow + Reverse Second Half
Twin sum = node[i].val + node[n-1-i].val. Find maximum.
Solutions
# Python
def pairSum(head):
# Find middle
slow = fast = head
while fast and fast.next:
slow = slow.next; fast = fast.next.next
# Reverse second half
prev, cur = None, slow
while cur:
nxt = cur.next; cur.next = prev; prev = cur; cur = nxt
# Compute max twin sum
ans = 0
first, second = head, prev
while second:
ans = max(ans, first.val + second.val)
first = first.next; second = second.next
return ans
// Java
public int pairSum(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
ListNode prev = null, cur = slow;
while (cur != null) { ListNode nxt = cur.next; cur.next = prev; prev = cur; cur = nxt; }
int ans = 0;
ListNode l1 = head, l2 = prev;
while (l2 != null) { ans = Math.max(ans, l1.val + l2.val); l1 = l1.next; l2 = l2.next; }
return ans;
}
Complexity
- Time: O(n)
- Space: O(1)
Advertisement