-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path2130.Maximum-Twin-Sum-of-a-Linked-List.java
59 lines (45 loc) · 1.28 KB
/
2130.Maximum-Twin-Sum-of-a-Linked-List.java
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
// https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/
// algorithms
// Easy (84.29%)
// Total Accepted: 8,372
// Total Submissions: 9,932
// solution 1
class Solution {
public int pairSum(ListNode head) {
ListNode slow = head, fast = head.next;
ListNode pre = null;
while (fast.next != null) {
fast = fast.next.next;
ListNode tmp = slow.next;
slow.next = pre;
pre = slow;
slow = tmp;
}
fast = slow.next;
slow.next = pre;
int res = fast.val + slow.val;
while (fast != null) {
res = Math.max(res, fast.val + slow.val);
fast = fast.next;
slow = slow.next;
}
return res;
}
}
// solution 2
class Solution {
public int pairSum(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int i = 0, j = list.size() - 1;
int res = list.get(i) + list.get(j);
while (++i < --j) {
int tmp = list.get(i) + list.get(j);
res = Math.max(res, tmp);
}
return res;
}
}