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。

相关推荐
2401_841495643 天前
【LeetCode刷题】二叉树的中序遍历
数据结构·python·算法·leetcode··递归·遍历
闻缺陷则喜何志丹6 天前
【树 链 菊花】P10418 [蓝桥杯 2023 国 A] 相连的边|普及+
c++·算法·蓝桥杯···菊花
量子炒饭大师1 个月前
Cyber骇客神经塔尖协议 ——【初阶数据结构与算法】堆
c语言·数据结构·c++·二叉树·github·
Espresso Macchiato1 个月前
Leetcode 3791. Number of Balanced Integers in a Range
leetcode hard·leetcode周赛482·leetcode 3791
Espresso Macchiato1 个月前
Leetcode 3782. Last Remaining Integer After Alternating Deletion Operations
迭代·leetcode hard·leetcode双周赛172·leetcode 3782
Espresso Macchiato1 个月前
Leetcode 3768. Minimum Inversion Count in Subarrays of Fixed Length
滑动窗口·leetcode hard·leetcode双周赛171·leetcode 3768
Espresso Macchiato1 个月前
Leetcode 3785. Minimum Swaps to Avoid Forbidden Values
leetcode hard·leetcode周赛481·leetcode 3785
Espresso Macchiato1 个月前
Leetcode 3786. Total Sum of Interaction Cost in Tree Groups
leetcode hard·leetcode 3786·leetcode周赛481
罗湖老棍子1 个月前
C++ 自定义排序与优先队列运算符重载
数据结构·c++·算法··优先队列·运算符重载
scx201310041 个月前
20251122树的直径、重心、中心
·直径·重心·中心