Skip to content

Commit e35fb56

Browse files
authored
Create 2130-maximum-twin-sum-of-a-linked-list.kt
1 parent ae57b64 commit e35fb56

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+
* Example:
3+
* var li = ListNode(5)
4+
* var v = li.`val`
5+
* Definition for singly-linked list.
6+
* class ListNode(var `val`: Int) {
7+
* var next: ListNode? = null
8+
* }
9+
*/
10+
class Solution {
11+
fun pairSum(head: ListNode?): Int {
12+
var slow = head
13+
var fast = head
14+
var prev: ListNode? = null
15+
16+
while(fast != null && fast.next != null) {
17+
fast = fast.next.next
18+
val temp = slow?.next
19+
slow?.next = prev
20+
prev = slow
21+
slow = temp
22+
}
23+
24+
var res = 0
25+
while(slow != null && prev != null) { // only need to check if either one of these != null, I check both for null safety warnings
26+
res = maxOf(res, slow.value!! + prev.value!!)
27+
prev = prev.next
28+
slow = slow.next
29+
}
30+
31+
return res
32+
}
33+
34+
val ListNode.value get()= this.`val`
35+
}

0 commit comments

Comments
 (0)