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 = (
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.
using System.Collections.Generic;
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
public class Solution {
public int PairSum(ListNode head) {
List<int> values = new List<int>();
ListNode current = head;
while (current != null) {
values.Add(current.val);
current = current.next;
}
int maxTwinSum = 0;
int n = values.Count;
for (int i = 0; i < n / 2; i++) {
int twinSum = values[i] + values[n - 1 - i];
maxTwinSum = Math.Max(maxTwinSum, twinSum);
}
return maxTwinSum;
}
}
The C# solution makes use of lists for storing node values, allowing direct computation for twin sums after all values are recorded.