Maximum Points After Collecting Coins From All Nodes — LeetCode 2920 Python Solution
- Problem
- #2920
- Pattern
- Bit Manipulation
- Reading time
- 4 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M) |
| Space | O(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.