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: Maximize Sum of Player Indices012→2→0→1Example: Start from player 2, k=4 passesPath: 2 → 1 → 0 → 2 → 1Score: 2 + 1 + 0 + 2 + 1 = 6Maximum Score: 6
Understanding the Visualization
1
Input
Array receiver=[2,0,1] and k=4 passes
2
Process
Try different starting positions and simulate ball passing
3
Output
Return maximum score from all possible starting positions
Key Takeaway
🎯 Key Insight: Binary lifting allows us to handle k up to 10^10 by precomputing jumps in powers of 2
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