Leetcode 3068. Find the Maximum Sum of Node Values

  • [Leetcode 3068. Find the Maximum Sum of Node Values](#Leetcode 3068. Find the Maximum Sum of Node Values)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题虽然标记为一道hard的题目,但其实就是一个脑筋急转弯的题目。

我们只需要想明白一点即可:

  • 由于异或操作满足x^y^y = x,对于一棵联通树,我们总可以通过有限次对相邻边地操作,使得任意两点(u, v)转变为(u^z, v^z),而其他所有的节点都不发生变化。

因此,我们只需要计算出所有点如果进行异或操作之后可以得到的改变量,然后将其从大到小进行排序,两两配对之后考察最大能够获得多少累积增长即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maximumValueSum(self, nums: List[int], k: int, edges: List[List[int]]) -> int:
        delta = sorted([(x ^ k) - x for i, x in enumerate(nums)], reverse=True)
        i, n = 0, len(delta)
        ans = sum(nums)
        while i+1 < n and delta[i] + delta[i+1] > 0:
            ans += delta[i] + delta[i+1]
            i += 2
        return ans

提交代码评测得到:耗时972ms,占用内存28MB。

相关推荐
代码AC不AC19 天前
【数据结构】树的介绍
c语言·数据结构··学习分享·技术交流
Espresso Macchiato22 天前
Leetcode 3500. Minimum Cost to Divide Array Into Subarrays
leetcode·动态规划·leetcode hard·leetcode 3500·leetcode双周赛153
大小胖虎1 个月前
数据结构——第五章:树与二叉树
c语言·数据结构·c++·算法·二叉树··专业课
神里流~霜灭1 个月前
数据结构:树的先序遍历、中序遍历、后序遍历和层序遍历
c语言·数据结构·c++·算法·二叉树·
神里流~霜灭1 个月前
数据结构:二叉树(一)·(重点)
数据结构·c++·算法·链表·贪心算法·二叉树·
Vitalia1 个月前
图论入门【数据结构基础】:什么是树?如何表示树?
数据结构·算法·图论·
Espresso Macchiato1 个月前
Leetcode 3490. Count Beautiful Numbers
动态规划·leetcode hard·leetcode 3490·leetcode周赛441·满足条件的自然数
DARLING Zero two♡2 个月前
【初阶数据结构】森林里的树影 “堆” 光:堆
c语言·数据结构·c++··
江奖蒋犟2 个月前
【初阶数据结构】树和二叉树
数据结构·
Espresso Macchiato3 个月前
Leetcode 3449. Maximize the Minimum Game Score
贪婪算法·二分法·leetcode hard·leetcode 3449·leetcode周赛436