31/38
Part 7 of 7 · Follow-upsLearn and do
When a parent's choice depends on its child's, return two numbers from each subtree
A prep site lists the largest sum of tree values with no two chosen nodes next to each other for an Airbnb senior loop (1 source). Next to each other means parent and child.
One number per subtree isn't enough, because the parent's choice depends on whether the child was taken. So each node returns two:
take: the best total if it's taken. Then its children must be skipped.skip: the best total if it's skipped. Then each child is free to be either.
VALUE = {"Europe": 5, "Portugal": 4, "Spain": 6, "Lisbon District": 3, "Porto District": 2,
"Lisbon": 8, "Sintra": 1, "Cascais": 2, "Porto": 7, "Andalusia": 9, "Catalonia": 3,
"Seville": 4, "Granada": 4}
print(best_without_neighbors(children, VALUE, "Europe"))
36
Lisbon District has value 3, and its leaves Lisbon, Sintra and Cascais have 8, 1 and 2. What's the best total there, never taking a parent and its child?
Pick an answer above to see the rest