Skip to content

Commit 1e282d4

Browse files
authored
Merge pull request #2699 from tahzeer/patch-2
Create 2130-maximum-twin-sum-of-a-linked-list.cpp
2 parents 723a252 + 58b561a commit 1e282d4

File tree

1 file changed

+49
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)