Maximize Value of Function in a Ball Passing Game

You are given an integer array receiver of length n and an integer k. n players are playing a ball-passing game.

You choose the starting player, i. The game proceeds as follows: player i passes the ball to player receiver[i], who then passes it to receiver[receiver[i]], and so on, for k passes in total. The game's score is the sum of the indices of the players who touched the ball, including repetitions, i.e. i + receiver[i] + receiver[receiver[i]] + ... + receiver^k[i].

Return the maximum possible score.

Notes:

  • receiver may contain duplicates.
  • receiver[i] may be equal to i.
Example 1
Inputreceiver = [2,0,1], k = 4
Output6
Starting with player i = 2, the score after 4 passes is 2 + 1 + 0 + 2 + 1 = 6, which is maximum.
Example 2
Inputreceiver = [1,1,1,2,3], k = 3
Output10
Starting with player i = 4, the score after 3 passes is 4 + 3 + 2 + 1 = 10, which is maximum.

Constraints

  • 1 <= receiver.length == n <= 10^5
  • 0 <= receiver[i] <= n - 1
  • 1 <= k <= 10^10

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate