Skip to content

Latest commit

 

History

History
83 lines (65 loc) · 2.19 KB

_2130. Maximum Twin Sum of a Linked List.md

File metadata and controls

83 lines (65 loc) · 2.19 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 21, 2024

Last updated : June 21, 2024


Related Topics : Linked List, Two Pointers, Stack

Acceptance Rate : 81.08 %


Solutions

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        vals = []

        while head :
            vals.append(head.val)
            head = head.next

        return max([vals[i] + vals[len(vals) - 1 - i] for i in range(ceil(len(vals) / 2))])
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        beforeHalf = None
        half = head
        temp = head

        # Finding halfway mark
        while temp and temp.next:
            beforeHalf = half
            half = half.next
            temp = temp.next.next

        # Reverse 2nd half
        toVisit = half
        beforeHalf.next = None
        while toVisit :
            temp = toVisit.next
            toVisit.next = beforeHalf.next
            beforeHalf.next = toVisit
            toVisit = temp
        
        maxx = 0

        left = head
        right = beforeHalf.next
        while right :
            maxx = max(maxx, left.val + right.val)
            left = left.next
            right = right.next

        return maxx