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.
1struct ListNode {
2 int val;
3 struct ListNode *next;
4};
5
6struct ListNode* reverseList(struct ListNode* head) {
7 struct ListNode* prev = NULL;
8 struct ListNode* curr = head;
9 while (curr) {
10 struct ListNode* nextTemp = curr->next;
11 curr->next = prev;
12 prev = curr;
13 curr = nextTemp;
14 }
15 return prev;
16}
17
18int pairSum(struct ListNode* head) {
19 struct ListNode* slow = head;
20 struct ListNode* fast = head;
21 while (fast && fast->next) {
22 slow = slow->next;
23 fast = fast->next->next;
24 }
25 struct ListNode* secondHalf = reverseList(slow);
26 int maxTwinSum = 0;
27 struct ListNode* firstHalf = head;
28 while (secondHalf) {
29 int twinSum = firstHalf->val + secondHalf->val;
30 if(twinSum > maxTwinSum) maxTwinSum = twinSum;
31 firstHalf = firstHalf->next;
32 secondHalf = secondHalf->next;
33 }
34 return maxTwinSum;
35}
This solution involves reversing the second half of the linked list, which is achieved with the reverseList
function. After that, we compare nodes from the start of the first and the new reversed lists to find and return the maximum twin sum.
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.
1
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.