Skip to content

Commit a901e14

Browse files
authored
Create maximum-twin-sum-of-a-linked-list.cpp
1 parent 7fd1f30 commit a901e14

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode() : val(0), next(nullptr) {}
10+
* ListNode(int x) : val(x), next(nullptr) {}
11+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
12+
* };
13+
*/
14+
class Solution {
15+
public:
16+
int pairSum(ListNode* head) {
17+
ListNode dummy(0, head);
18+
auto slow = dummy.next, fast = dummy.next;
19+
while (fast->next && fast->next->next) {
20+
slow = slow->next;
21+
fast = fast->next->next;
22+
}
23+
int result = 0;
24+
auto head2 = reverseList(slow);
25+
while (head) {
26+
result = max(result, head->val + head2->val);
27+
head = head->next;
28+
head2 = head2->next;
29+
}
30+
return result;
31+
}
32+
33+
private:
34+
ListNode* reverseList(ListNode* head) {
35+
ListNode dummy;
36+
while (head) {
37+
auto tmp = head->next;
38+
head->next = dummy.next;
39+
dummy.next = head;
40+
head = tmp;
41+
}
42+
return dummy.next;
43+
}
44+
};

0 commit comments

Comments
 (0)