class Solution {
public int pairSum(ListNode head) {
// Find middle
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse second half
ListNode prev = null;
while (slow != null) {
ListNode next = slow.next;
slow.next = prev;
prev = slow;
slow = next;
}
// Calculate maximum twin sum
int ans = 0;
ListNode first = head;
ListNode second = prev;
while (second != null) {
ans = Math.max(ans, first.val + second.val);
first = first.next;
second = second.next;
}
return ans;
}
}
TIME COMPLEXITY
SPACE COMPLEXITY