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。

相关推荐
闪电麦坤9515 小时前
数据结构:从前序遍历序列重建一棵二叉搜索树 (Generating from Preorder)
数据结构··二叉搜索树
闪电麦坤9515 小时前
数据结构:二叉树的遍历 (Binary Tree Traversals)
数据结构·二叉树·
闪电麦坤954 天前
数据结构:在二叉搜索树中插入元素(Insert in a BST)
数据结构·二叉树··二叉搜索树
闪电麦坤954 天前
数据结构:用链式队列实现层序遍历 (Level-order Traversal)
数据结构··遍历
闪电麦坤954 天前
数据结构:迭代方法(Iteration)实现树的遍历
数据结构·二叉树·
闪电麦坤955 天前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
闪电麦坤955 天前
数据结构:N叉树 (N-ary Tree)
数据结构·
Alfred king1 个月前
面试150 建立四叉树
矩阵··数组·分治
Espresso Macchiato1 个月前
Leetcode 3624. Number of Integers With Popcount-Depth Equal to K II
leetcode hard·segment tree·分段树·leetcode 3624·leetcode周赛459
小指纹1 个月前
初识 二叉树
c++·算法·二叉树·