-
Notifications
You must be signed in to change notification settings - Fork 0
/
2130.c
121 lines (87 loc) · 2.01 KB
/
2130.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdio.h>
#include <stdlib.h>
//Definition for singly-linked list.
struct ListNode {
int val;
struct ListNode *next;
};
int pairSum(struct ListNode* head){
struct ListNode *out = head;
struct ListNode *half = head;
int size = 0;
int ans = 0;
while(out != NULL)
{
out = out->next;
size++;
}
int* d = (int*)malloc(sizeof(int) * (size / 2));
int i = 0;
for(i = 0; i < size / 2; ++i)
{
d[i] = half->val;
half = half->next;
}
for(i = size / 2 - 1; i >= 0; --i)
{
d[i] += half->val;
half = half->next;
}
ans = d[0];
for(i = 1; i < size / 2; ++i)
{
ans = ans > d[i] ? ans : d[i];
}
return ans;
}
/*
Best Solution
//Definition for singly-linked list.
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* middle(struct ListNode *head){
if(head==NULL||head->next==NULL){
return head;
}
struct ListNode *fast=head;
struct ListNode *slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
struct ListNode* reverse(struct ListNode *head){
if(head==NULL||head->next==NULL){
return head;
}
struct ListNode *curr=head,*prev=NULL,*next=NULL;
while(curr){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
head=prev;
return head;
}
int pairSum(struct ListNode* head){
if(head==NULL){
return -1;
}
struct ListNode *first=head;
struct ListNode *tmp=middle(head);
struct ListNode *second=reverse(tmp);
int sum=INT_MIN;
while(second!=NULL){
if((first->val+second->val)>sum){
sum=(first->val+second->val);
}
first=first->next;
second=second->next;
}
return sum;
}
*/