Skip to content

Commit b947ac2

Browse files
authored
Create maximum-twin-sum-of-a-linked-list.py
1 parent a901e14 commit b947ac2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Definition for singly-linked list.
5+
class ListNode(object):
6+
def __init__(self, val=0, next=None):
7+
self.val = val
8+
self.next = next
9+
10+
11+
class Solution(object):
12+
def pairSum(self, head):
13+
"""
14+
:type head: Optional[ListNode]
15+
:rtype: int
16+
"""
17+
def reverseList(head):
18+
dummy = ListNode()
19+
while head:
20+
dummy.next, head.next, head = head, dummy.next, head.next
21+
return dummy.next
22+
23+
dummy = ListNode(next=head)
24+
slow = fast = dummy
25+
while fast.next and fast.next.next:
26+
slow, fast = slow.next, fast.next.next
27+
result = 0
28+
head2 = reverseList(slow)
29+
while head:
30+
result = max(result, head.val+head2.val)
31+
head, head2 = head.next, head2.next
32+
return result

0 commit comments

Comments
 (0)