Maximize Value of Function in a Ball Passing Game Problem
Description
LeetCode Problem 2836.
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:
receivermay contain duplicates.receiver[i]may be equal toi.
Example 1:
Input: receiver = [2,0,1], k = 4
Output: 6
Explanation:
Starting with player i = 2 the initial score is 2:
Pass Sender Index Receiver Index Score
1 2 1 3
2 1 0 3
3 0 2 5
4 2 1 6
Example 2:
Input: receiver = [1,1,1,2,3], k = 3
Output: 10
Explanation:
Starting with player i = 4 the initial score is 4:
Pass Sender Index Receiver Index Score
1 4 3 7
2 3 2 9
3 2 1 10
Constraints:
1 <= receiver.length == n <= 10^50 <= receiver[i] <= n - 11 <= k <= 10^10
Solution
Approach: Dynamic Programming + Binary Lifting
Simulating k passes from every start is too slow, so use binary lifting. Let f[i][j] be the player reached after 2^j passes from i, and g[i][j] the sum of the player IDs on those passes, excluding the last one.
For j = 0: f[i][0] = receiver[i] and g[i][0] = i. For larger j, f[i][j] = f[f[i][j-1]][j-1] and g[i][j] = g[i][j-1] + g[f[i][j-1]][j-1].
For each starting player, walk through the set bits of k, jumping by 2^j and accumulating g. Add the final player's ID and take the maximum over all starts.
Complexity: time O(n log k), space O(n log k).
Similar problem: 1483. Kth Ancestor of a Tree Node.
class Solution:
def getMaxFunctionValue(self, receiver: List[int], k: int) -> int:
n = len(receiver)
f = receiver[:]
g = list(range(n))
p = list(range(n))
t = [0] * n
while k:
if k & 1:
t = [t[i] + g[p[i]] for i in range(n)]
p = [f[x] for x in p]
k >>= 1
if k:
g = [g[i] + g[f[i]] for i in range(n)]
f = [f[x] for x in f]
return max(t[i] + p[i] for i in range(n))