Skip to content

Commit 6880ead

Browse files
Merge pull request #3394 from drxlx/2130-maximum-twin-sum-of-a-linked-list
2 parents 36da36e + 8ebf336 commit 6880ead

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/
3+
*/
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* public class ListNode {
8+
* public var val: Int
9+
* public var next: ListNode?
10+
* public init() { self.val = 0; self.next = nil; }
11+
* public init(_ val: Int) { self.val = val; self.next = nil; }
12+
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
13+
* }
14+
*/
15+
class Solution {
16+
func pairSum(_ head: ListNode?) -> Int {
17+
var slow = head
18+
var fast = head
19+
var prev: ListNode?
20+
while fast != nil && fast?.next != nil {
21+
fast = fast?.next?.next
22+
var tmp = slow?.next
23+
slow?.next = prev
24+
prev = slow
25+
slow = tmp
26+
}
27+
var res = 0
28+
while slow != nil {
29+
res = max(res, prev!.val + slow!.val)
30+
prev = prev?.next
31+
slow = slow?.next
32+
}
33+
return res
34+
}
35+
}

0 commit comments

Comments
 (0)