-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2130-twinSum.c
61 lines (52 loc) · 1.33 KB
/
2130-twinSum.c
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
55
56
57
58
59
60
61
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val ;
struct ListNode* next ;
} ;
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* current = head;
struct ListNode* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
int pairSum(struct ListNode* head) {
if (head == NULL) return 0;
// Step 1: Find the middle of the linked list
struct ListNode* slow = head;
struct ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
// Step 2: Reverse the second half of the linked list
struct ListNode* secondHalf = reverseList(slow);
// Step 3: Calculate the maximum twin sum
int maxTwinSum = 0;
struct ListNode* firstHalf = head;
while (secondHalf != NULL) {
int twinSum = firstHalf->val + secondHalf->val;
if (twinSum > maxTwinSum) {
maxTwinSum = twinSum;
}
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
}
return maxTwinSum;
}
int main ()
{
}