Sponsored
Sponsored
The idea is to reverse the second half of the linked list and utilize the twin's definition by simultaneously traversing the first half from the beginning and the reversed half from the end. As you do this traversal, calculate the twin sums and keep track of the maximum.
Steps:
Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(1), as we only use a constant amount of additional space.
1function ListNode(val, next) {
2 this.val = (val===undefined ? 0 : val)
3 this.next = (next===undefined ? null : next)
4}
5
6var reverseList = function(head) {
7 let prev = null;
8 let current = head;
9 while (current !== null) {
10 let nextTemp = current.next;
11 current.next = prev;
12 prev = current;
13 current = nextTemp;
14 }
15 return prev;
16};
17
18var pairSum = function(head) {
19 let slow = head;
20 let fast = head;
21 while (fast !== null && fast.next !== null) {
22 slow = slow.next;
23 fast = fast.next.next;
24 }
25
26 let secondHalf = reverseList(slow);
27 let maxTwinSum = 0;
28 let firstHalf = head;
29 while (secondHalf !== null) {
30 let twinSum = firstHalf.val + secondHalf.val;
31 maxTwinSum = Math.max(maxTwinSum, twinSum);
32 firstHalf = firstHalf.next;
33 secondHalf = secondHalf.next;
34 }
35
36 return maxTwinSum;
37};
In this JavaScript solution, the list is divided and the second portion is reversed. The maximum twin sum is then calculated by summing the nodes from the two ends.
This approach makes use of an auxiliary array where we store the values of the linked list nodes. Once stored, we can leverage the structure of the list to easily compute twin sums using simple array indexing.
Steps:
Time Complexity: O(n).
Space Complexity: O(n), due to the auxiliary array.
An auxiliary array is used to read the linked list node values. Then, a loop calculates the twin sums through array indices and computes the maximum sum.