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。

相关推荐
Espresso Macchiato5 天前
Leetcode 3702. Longest Subsequence With Non-Zero Bitwise XOR
leetcode medium·异或操作·leetcode 3702·leetcode周赛470
Espresso Macchiato7 天前
Leetcode 3700. Number of ZigZag Arrays II
动态规划·leetcode hard·矩阵乘法·leetcode 3700·leetcode周赛469
Espresso Macchiato8 天前
Leetcode 3695. Maximize Alternating Sum Using Swaps
并查集·leetcode hard·dsu·uf·leetcode 3695·leetcode双周赛166
CS创新实验室8 天前
第7章树和二叉树:树的基本概念
数据结构·二叉树··基本概念
南莺莺11 天前
树的存储结构
数据结构·算法·
阿方.9181 个月前
《树与二叉树详解:概念、结构及应用》
数据结构·二叉树··知识分享
_OP_CHEN1 个月前
数据结构(C语言篇):(十一)二叉树概念介绍
c语言·开发语言·数据结构·二叉树·学习笔记··
稳兽龙1 个月前
codeforces(1045)(div2)D. Sliding Tree
c++·算法··路径树
闪电麦坤951 个月前
数据结构:红黑树(Red-Black Tree)
数据结构··红黑树
工藤新一¹1 个月前
C/C++ 数据结构 —— 树(2)
c语言·数据结构·c++·二叉树··c/c++