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。

相关推荐
fu的博客9 天前
【数据结构10】满/完全二叉树、顺序/链式存储
数据结构·
uesowys10 天前
算法开发指导-数据结构-Tree
数据结构·算法·
2013编程爱好者20 天前
【C++】树的基础
数据结构·二叉树··二叉树的遍历
码农幻想梦20 天前
3555. 二叉树(北京邮电大学考研机试题)
考研·
蜕变的小白20 天前
数据结构:队列与二叉树精讲
数据结构··队列
码农幻想梦21 天前
3471. 二叉树
数据结构·
2401_8414956424 天前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
2401_8414956424 天前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
2401_841495641 个月前
【LeetCode刷题】对称二叉树
数据结构·python·算法·leetcode·二叉树··递归