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.
1#include <iostream>
2
3struct ListNode {
4 int val;
5 ListNode *next;
6 ListNode(int x) : val(x), next(NULL) {}
7};
8
9class Solution {
10public:
11 ListNode* reverseList(ListNode* head) {
12 ListNode* prev = nullptr;
13 ListNode* current = head;
14 while (current) {
15 ListNode* nextTemp = current->next;
16 current->next = prev;
17 prev = current;
18 current = nextTemp;
19 }
20 return prev;
21 }
22
23 int pairSum(ListNode* head) {
24 ListNode* slow = head;
25 ListNode* fast = head;
26 while (fast && fast->next) {
27 slow = slow->next;
28 fast = fast->next->next;
29 }
30
31 ListNode* secondHalf = reverseList(slow);
32 int maxTwinSum = 0;
33
34 ListNode* firstHalf = head;
35 while (secondHalf) {
36 int twinSum = firstHalf->val + secondHalf->val;
37 maxTwinSum = std::max(maxTwinSum, twinSum);
38 firstHalf = firstHalf->next;
39 secondHalf = secondHalf->next;
40 }
41
42 return maxTwinSum;
43 }
44};
The solution first finds the midpoint of the linked list. It then reverses the second half and calculates the twin sums while updating the maximum value. Finally, it returns 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.
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.