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。

相关推荐
问道飞鱼2 天前
每日学习一个数据结构-树
数据结构·学习·
修修修也9 天前
【数据结构】什么是二叉搜索(排序)树?
开发语言·数据结构·笔记·二叉树··二叉搜索树
X² 编程说10 天前
16.面试算法-树的层次遍历与相关面试题
数据结构·后端·算法·面试·深度优先··广度优先
no_play_no_games11 天前
会议dfs树
c++·算法·深度优先·图论·
初级代码游戏1 个月前
github源码指引:共享内存、数据结构与算法:树形结构ListTree
链表·github··共享内存
朱皮皮呀1 个月前
数据结构-堆
数据结构·算法·二叉树··
zhoupenghui1681 个月前
数据结构-树
数据结构·二叉树···完全二叉树
Jcqsunny1 个月前
[图论]游戏
c++·深度优先·图论·
Espresso Macchiato2 个月前
Leetcode 3261. Count Substrings That Satisfy K-Constraint II
滑动窗口·leetcode hard·leetcode周赛411·leetcode 3261·累积数组
Espresso Macchiato2 个月前
Leetcode 3260. Find the Largest Palindrome Divisible by K
leetcode hard·回文·分类讨论·leetcode 3260·leetcode周赛411