Company: Fantasy Premier League
Difficulty: medium
Chain Square You are given a directed tree with N nodes, described by an array A of size N - 1 : for every i with 1 ≤ i < N , there is a directed edge from node A[i] to node i+1 . You may repeatedly apply the following operation: Choose any edge in the tree and remove it, which splits that tree into two separate trees. Keep removing edges until the tree is broken into a collection of directed chains. Your score is the sum, taken over all chains in that collection, of the square of each chain's length. Report the largest score that can be achieved. Notes A directed chain is a directed tree in which every node has at most one outgoing edge and at most one incoming edge . A directed chain's length is its number of nodes. Indices are 1 -based. Input Format The first line contains an integer N , representing the size of the tree. The second line contains N - 1 space-separated integers representing the array A . Output Format Print a single integer: the largest score that can be achieved.