Maximum Points After Collecting Coins From All Nodes — LeetCode 2920 Python Solution

HardBit ManipulationTreeDepth-First SearchMemoizationArrayDynamic Programming
Problem
#2920
Reading time
4 min

The problem

There exists an undirected tree rooted at node 0 with n nodes labeled from 0 to n - 1. You are given a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Example

Input
edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5
Output
11
Explanation
Collect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.

Python solution

Python
class Solution:
    def maximumPoints(self, edges: List[List[int]], coins: List[int], k: int) -> int:
        @cache
        def dfs(i: int, fa: int, j: int) -> int:
            a = (coins[i] >> j) - k
            b = coins[i] >> (j + 1)
            for c in g[i]:
                if c != fa:
                    a += dfs(c, i, j)
                    if j < 14:
                        b += dfs(c, i, j + 1)
            return max(a, b)

        n = len(coins)
        g = [[] for _ in range(n)]
        for a, b in edges:
            g[a].append(b)
            g[b].append(a)
        ans = dfs(0, -1, 0)
        dfs.cache_clear()
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(n \times \log M) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2920. Maximum Points After Collecting Coins From All Nodes is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2920. Maximum Points After Collecting Coins From All Nodes?
LeetCode 2920. Maximum Points After Collecting Coins From All Nodes is rated Hard on LeetCode.
What is the time complexity of LeetCode 2920. Maximum Points After Collecting Coins From All Nodes?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 2920. Maximum Points After Collecting Coins From All Nodes?
The Python solution on this page uses O(n \times \log M) auxiliary space.
What topics does LeetCode 2920. Maximum Points After Collecting Coins From All Nodes cover?
LeetCode 2920. Maximum Points After Collecting Coins From All Nodes is tagged Bit Manipulation, Tree, Depth-First Search, Memoization, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview