A fast-growing startup's org chart is a tree of n employees numbered 0 to n - 1, where employee 0 is the CEO and has no manager. For every other employee i (1 <= i <= n - 1), employee par_i is their direct manager, and the reporting relationship between employee i and par_i carries a mentorship bonus of score_i (a nonnegative integer measuring how well the pair works together).
HR wants to formalize a set of mentorship pairings, where each pairing links an employee directly to their own manager (a pairing may only use an existing reporting relationship, never any other pair of employees). To keep responsibilities clear, every employee -- whether acting as the manager or the report in a pairing -- may be part of at most one formalized pairing. Some employees may end up in zero pairings.
Determine the maximum possible sum of mentorship bonuses HR can lock in, subject to this one-pairing-per-employee limit.
Print a single integer: the maximum total mentorship bonus achievable.
Example 1
Input
4 0 5 0 1 1 10
Expected
11
Explanation
Employee 0 is the CEO; employees 1 and 2 report directly to the CEO (bonuses 5 and 1), and employee 3 reports to employee 1 (bonus 10). Pairing employee 1 with employee 3 (bonus 10) beats pairing the CEO with employee 1 (bonus 5), because it frees the CEO to pair with employee 2 (bonus 1) instead. Total = 10 + 1 = 11, via pairings (1,3) and (0,2); employee 1 cannot also pair with the CEO once it is paired with employee 3.
Example 2
Input
2 0 100
Expected
100
Explanation
There is only one employee besides the CEO, and only one possible pairing: employee 1 with the CEO, bonus 100. HR locks it in for a total of 100.
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 →