Maximize Value of Function in a Ball Passing Game - Problem

You are given an integer array receiver of length n and an integer k. There are n players 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.

The score formula is: i + receiver[i] + receiver[receiver[i]] + ... + receiver(k)[i]

Return the maximum possible score.

Note: receiver may contain duplicates and receiver[i] may be equal to i.

Input & Output

Example 1 — Basic Case
$ Input: receiver = [2,0,1], k = 4
Output: 6
💡 Note: Starting from player 1: 1→0→2→1→0. Score = 1+0+2+1+0 = 4. Starting from player 2: 2→1→0→2→1. Score = 2+1+0+2+1 = 6. Maximum is 6.
Example 2 — Self-Loop
$ Input: receiver = [1,1,1,2,3], k = 3
Output: 10
💡 Note: Starting from player 4: 4→3→2→1. Score = 4+3+2+1 = 10. This gives the maximum score since we start from the highest index and move to progressively smaller indices.
Example 3 — Small k
$ Input: receiver = [1,1], k = 1000
Output: 1001
💡 Note: Starting from player 1: stays at 1 for all 1001 positions (including start). Score = 1 × 1001 = 1001.

Constraints

  • 1 ≤ receiver.length ≤ 105
  • 0 ≤ receiver[i] ≤ n - 1
  • 1 ≤ k ≤ 1010

Visualization

Tap to expand
Ball Passing Game - Maximum Score INPUT receiver = [2, 0, 1] 2 i=0 0 i=1 1 i=2 Pass Graph: 0 1 2 2 --> 1 --> 0 --> k = 4 (number of passes) n = 3 (players) ALGORITHM STEPS 1 Binary Lifting Precompute 2^j jumps 2 Try Each Start Test starting from i=0,1,2 3 Simulate k Passes Sum indices along path 4 Track Maximum Keep best score found Trace from i=2: Pass 1: 2 --> 1 (sum=2) Pass 2: 1 --> 0 (sum=2+1=3) Pass 3: 0 --> 2 (sum=3+0=3) Pass 4: 2 --> 1 (sum=3+2=5) Final: 5 + 1 = 6 FINAL RESULT Best starting player: i = 2 Optimal Path: 2 1 0 2 1 Sum: 2+1+0+2+1 = 6 Output: 6 OK - Maximum Score Found All starting positions tested Key Insight: The graph forms cycles since each player has exactly one receiver. We simulate k passes from each starting position and track the sum of all visited indices. Binary lifting optimizes large k values by precomputing jumps of power-of-2 lengths, reducing time complexity to O(n log k). TutorialsPoint - Maximize Value of Function in a Ball Passing Game | Optimal Solution
Asked in
Google 25 Meta 18 Amazon 15
25.8K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen