|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2130. Maximum Twin Sum of a Linked List |
| 4 | +# https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. |
| 9 | +
|
| 10 | +For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. |
| 11 | +The twin sum is defined as the sum of a node and its twin. |
| 12 | +
|
| 13 | +Given the head of a linked list with even length, return the maximum twin sum of the linked list. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: head = [5,4,2,1] |
| 17 | +Output: 6 |
| 18 | +Explanation: |
| 19 | +Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6. |
| 20 | +There are no other nodes with twins in the linked list. |
| 21 | +Thus, the maximum twin sum of the linked list is 6. |
| 22 | +
|
| 23 | +Example 2: |
| 24 | +Input: head = [4,2,2,3] |
| 25 | +Output: 7 |
| 26 | +Explanation: |
| 27 | +The nodes with twins present in this linked list are: |
| 28 | +- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. |
| 29 | +- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. |
| 30 | +Thus, the maximum twin sum of the linked list is max(7, 4) = 7. |
| 31 | +
|
| 32 | +Example 3: |
| 33 | +Input: head = [1,100000] |
| 34 | +Output: 100001 |
| 35 | +Explanation: |
| 36 | +There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001. |
| 37 | +
|
| 38 | +Constraints: |
| 39 | +The number of nodes in the list is an even integer in the range [2, 105]. |
| 40 | +1 <= Node.val <= 105 |
| 41 | +=end |
| 42 | + |
| 43 | +# Definition for singly-linked list. |
| 44 | +# class ListNode |
| 45 | +# attr_accessor :val, :next |
| 46 | +# def initialize(val = 0, _next = nil) |
| 47 | +# @val = val |
| 48 | +# @next = _next |
| 49 | +# end |
| 50 | +# end |
| 51 | +# @param {ListNode} head |
| 52 | +# @return {Integer} |
| 53 | +def pair_sum(head) |
| 54 | + slow = fast = head |
| 55 | + stack = [] |
| 56 | + |
| 57 | + while fast&.next |
| 58 | + stack << slow.val |
| 59 | + slow = slow.next |
| 60 | + fast = fast.next.next |
| 61 | + end |
| 62 | + |
| 63 | + max = 0 |
| 64 | + while (val = stack.pop) |
| 65 | + max = [val + slow.val, max].max |
| 66 | + slow = slow.next |
| 67 | + end |
| 68 | + |
| 69 | + max |
| 70 | +end |
0 commit comments