A company has N employees, numbered 1 through N, where employee 1 is the CEO and has no manager. Every other employee i (2 <= i <= N) reports directly to exactly one manager, given as p_i, and an employee may have any number of direct reports, including zero. A management chain starting at the CEO is a path that begins at employee 1 and repeatedly moves to a direct report, ending at some employee who has no direct reports of their own; its length is the number of employees on that path, counting both the CEO and the final employee. Determine the length of the longest such management chain in the company.
Print a single integer: the number of employees on the longest management chain starting at the CEO.
Example 1
Input
7 1 1 3 3 4 4
Expected
4
Explanation
Employee 1 (CEO) directly manages 2 and 3; employee 3 manages 4 and 5; employee 4 manages 6 and 7. The chain 1 -> 3 -> 4 -> 6 (or 7) has 4 employees, and no chain in this hierarchy is longer, so the answer is 4.
Example 2
Input
5 1 1 1 1
Expected
2
Explanation
Employees 2, 3, 4, and 5 all report directly to the CEO (employee 1), so the hierarchy is completely flat. Every chain from the CEO to another employee has exactly 2 employees, so the longest chain has length 2.
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 →