2130. Maximum Twin Sum of a Linked List
Solution
Section titled “Solution”class ListNode { val: number; next: ListNode | null; constructor(val?: number, next?: ListNode | null) { this.val = val === undefined ? 0 : val; this.next = next === undefined ? null : next; }}
function pairSum(head: ListNode | null): number { if (head?.next && !head?.next?.next) { return head.val + head.next.val; }
const arr = []; let n = 0; let currentNode = head;
while (currentNode) { n++; arr.push(currentNode.val); currentNode = currentNode.next; }
let twinSum = 0;
for (let i = 0; i < arr.length / 2; i++) { twinSum = Math.max(twinSum, arr[i] + arr[n - 1 - i]); }
return twinSum;}
const first = new ListNode(5);const second = new ListNode(4);const third = new ListNode(2);const fourth = new ListNode(1);
first.next = second;second.next = third;third.next = fourth;
pairSum(first);