progress

~/problems / Trees / Tree DP

Pruning a diseased fruit tree

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A fruit tree has junctions 0 .. n-1: 0 is the trunk, parent[i] is the junction below i (parent[0] == -1), and value[i] is its fruit, negative where the wood is diseased. Sawing above any junction i != 0 removes i and everything above it, at cut_cost per cut.

Implement best_harvest(parent: list[int], value: list[int], cut_cost: int) -> int: the best total still attached to the trunk, minus the cuts' cost.

#        0 (3)
#       /     \
#   1 (-2)    2 (4)
#   /    \
# 3 (5)  4 (-6)
best_harvest([-1, 0, 0, 1, 1], [3, -2, 4, 5, -6], 1)  # 9   cut only junction 4: 3 - 2 + 4 + 5 - 1
best_harvest([-1, 0], [1, -1], 5)                     # 0   a cut costs more than it saves

Up to 100,000 junctions, numbered in no particular order; |value[i]| <= 1000, 0 <= cut_cost <= 1000.

⭐ Bonus: a speed test on a 100,000-junction chain earns a star if you traverse iteratively (recursion that deep hits Python's limit).

Show hint

keep[v] = value[v] + sum of max(keep[c], -cut_cost) over the children c; the answer is keep[0]. Process children before parents, e.g. in reverse BFS order.

Topic: Tree DP. Post-order: each node returns a small tuple of states to its parent.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc