原题链接
https://leetcode-cn.com/problems/maximum-twin-sum-of-a-linked-list/
题目
在一个大小为 n 且 n 为 偶数 的链表中,对于 0 <= i <= (n / 2) - 1 的 i ,第 i 个节点(下标从 0 开始)的孪生节点为第 (n-1-i) 个节点 。
比方说,n = 4 那么节点 0 是节点 3 的孪生节点,节点 1 是节点 2 的孪生节点。这是长度为 n = 4 的链表中所有的孪生节点。
孪生和 定义为一个节点和它孪生节点两者值之和。
给你一个长度为偶数的链表的头节点 head ,请你返回链表的 最大孪生和 。
示例 1:
输入:head = [5,4,2,1]
输出:6
解释:
节点 0 和节点 1 分别是节点 3 和 2 的孪生节点。孪生和都为 6 。
链表中没有其他孪生节点。
所以,链表的最大孪生和是 6 。
示例 2:
输入:head = [4,2,2,3]
输出:7
解释:
链表中的孪生节点为:
- 节点 0 是节点 3 的孪生节点,孪生和为 4 + 3 = 7 。
- 节点 1 是节点 2 的孪生节点,孪生和为 2 + 2 = 4 。
所以,最大孪生和为 max(7, 4) = 7 。
示例 3:
输入:head = [1,100000]
输出:100001
解释:
链表中只有一对孪生节点,孪生和为 1 + 100000 = 100001 。
提示:
- 链表的节点数目是 [2, 105] 中的 偶数 。
- 1 <= Node.val <= 105
解题思路
- 首先得到链表长度n,创建一个变量max记录最大值
- n取长度的一半,将链表移动到中间位置
- 将后半部分链表反转
- 将反转后的链表与原链表当前值相加与max比较取最大值
- 比较完后反转过的链表与原链表同时向下移动一位
代码
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
* 查长度 */
function getListCount(head: ListNode | null) {
let cnt = 0
while (head) {
cnt++
head = head.next
}
return cnt
}
/**
*链表反转 */
function listReverse(head: ListNode) {
let n1: ListNode | null = null
let n2: ListNode | null = null
while (head) {
n2 = head.next
head.next = n1
n1 = head
head = n2
}
return n1
}
function pairSum(head: ListNode | null): number {
let n = getListCount(head)
let now = head
let max = -Infinity
n >>>= 1
while (now && n) {
now = now.next
n--
}
now = listReverse(now)
while (now) {
max = Math.max(now.val + head.val, max)
now = now.next
head = head.next
}
return max
};