【单向链表】2130. 链表最大孪生和

原题链接

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

解题思路

  1. 首先得到链表长度n,创建一个变量max记录最大值
  2. n取长度的一半,将链表移动到中间位置
  3. 将后半部分链表反转
  4. 将反转后的链表与原链表当前值相加与max比较取最大值
  5. 比较完后反转过的链表与原链表同时向下移动一位

代码

/**
 * 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
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值