A regional broadcast operator runs a relay network laid out as a tree of n towers, numbered 0 through n - 1, with tower 0 serving as the central hub. The network is described by n - 1 direct links between towers, and every tower is reachable from the hub through exactly one path (there are no cycles). Tower i currently holds an active equipment reserve worth strength[i] units.
You may decommission any subset of the towers. Decommissioning tower i banks strength[i] units of scrap value for you and drops that tower's contribution to zero. The network must remain live: for every path running from the hub down to an outpost tower (a tower with no towers beyond it), at least one tower on that path must be left active — the towers you decommission may never cover an entire hub-to-outpost path. Choose which towers to decommission so as to maximize the total scrap value collected while the network stays live.
A single integer: the maximum total scrap value obtainable while keeping the network live.
Example 1
Input
4 3 5 2 4 0 1 0 2 2 3
Expected
11
Explanation
Tower 0 is the hub, linked to tower 1 (strength 5) and tower 2 (strength 2), and tower 2 is linked onward to tower 3 (strength 4). There are two hub-to-outpost paths: 0-1 and 0-2-3. Tower 0 lies on both of them, so keeping only tower 0 active (strength 3) already keeps the whole network live, and every other tower can be decommissioned. That banks 5 + 2 + 4 = 11 units of scrap value, which is the maximum possible.
Example 2
Input
4 10 1 1 1 0 1 0 2 0 3
Expected
10
Explanation
Here the hub itself is expensive to keep (strength 10) while every branch tower is cheap (strength 1). Decommissioning the hub banks 10 units, but then each of the three branches 0-1, 0-2 and 0-3 needs its own active tower, so towers 1, 2 and 3 must all stay active. Total scrap value = 10, and no other choice beats it: keeping the hub instead only banks 1 + 1 + 1 = 3.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →