-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumTwinSumOfLinkedList_Day60.py
More file actions
68 lines (56 loc) · 1.62 KB
/
Copy pathMaximumTwinSumOfLinkedList_Day60.py
File metadata and controls
68 lines (56 loc) · 1.62 KB
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
# Brute Approach
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
arr = []
while head:
arr.append(head.val)
head = head.next
n = len(arr)
max_sum = 0
for i in range(n // 2):
max_sum = max(max_sum, arr[i] + arr[n - 1 - i])
return max_sum
# Better Approach
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
# Find middle using slow-fast pointers
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Push second half to stack
stack = []
while slow:
stack.append(slow.val)
slow = slow.next
max_sum = 0
curr = head
while stack:
max_sum = max(max_sum, curr.val + stack.pop())
curr = curr.next
return max_sum
#Optimal Approach
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
# Find middle (slow will be at mid)
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Reverse second half
prev = None
while slow:
nxt = slow.next
slow.next = prev
prev = slow
slow = nxt
# Compare and calculate max twin sum
max_sum = 0
first, second = head, prev
while second:
max_sum = max(max_sum, first.val + second.val)
first = first.next
second = second.next
return max_sum
# Time: O(n)
# Space: O(1)