forked from GDSC-IGDTUW-Autumn-of-Code-2022/dsa-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum Twin Sum of a Linked List.cpp
54 lines (51 loc) · 1.33 KB
/
Maximum Twin Sum of a Linked List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<bits/stdc++.h>
#define ll int
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int pairSum(ListNode* head) {
if(head==nullptr)
return 0;
ListNode* fast = head, *slow = head;
while(fast->next and fast->next->next)
fast = fast->next->next,slow = slow->next;
ListNode* pre = nullptr;
while(slow)
{
ListNode* nex = slow->next;
slow->next = pre;
pre = slow;
slow = nex;
}
ll ans = 0;
slow = head;
while(slow and pre)
ans = max(slow->val+pre->val, ans), slow = slow->next,pre = pre->next;
return ans;
}
ListNode* createList()
{
ListNode* head = new ListNode(-1);
ListNode* temp = head;
ll val = 0;
while(1)
{
cin>>val;
if(val==-1)
break;
ListNode* newNode = new ListNode(val);
temp->next = newNode;
temp = newNode;
}
return head->next;
}
int main()
{
ListNode* head = createList();
cout<<pairSum(head);
}