I am working on this problem: Maximum games played by winner . Quoted here for convenience:
There are N players which are playing a tournament. We need to find the maximum number of games the winner can play. In this tournament, two players are allowed to play against each other only if the difference between games played by them is not more than one.
Input :
N = 4
Output : 2
Maximum games winner can play = 2
Assume that player are P1, P2, P3 and P4
First two pairs will play lets (P1, P2) and
(P3, P4). Now winner of these two games will
play against each other, making total games
played by winner = 2
My confusion is with this below approach explained:
We can solve this problem by first computing minimum number of players required such that the winner will play x games. Once this is computed actual problem is just inverse of this. Now assume that dp[i] denotes minimum number of players required so that winner plays i games. We can write a recursive relation among dp values as, dp[i + 1] = dp[i] + dp[i – 1] because if runner up has played (i – 1) games and winner has played i games and all players against which they have played the match are disjoint, total games played by winner will be addition of those two sets of players. Above recursive relation can be written as dp[i] = dp[i – 1] + dp[i – 2]
Here is my understanding.
Let's say 4 players p1, p2, p3, p4.
The games are
Game 1: (p1, p2) winner p1
Game 2: (p3, p4) winner as p3
Game 3: (p1,p3) winner as p1
The winner is p1 and the runner is p3.
At Game 1, Runner p3 has played 0 games. so dp[i-1] = 0. Winner has played 1 game so dp[i] = 1. so dp[2] = 1 + 0 = 1. I am totally confused how to understand this approach towards solution.
Finally the solution is this:
int maxGameByWinner(int N)
{
int[] dp = new int[N];
// for 0 games, 1 player is needed
// for 1 game, 2 players are required
dp[0] = 1;
dp[1] = 2;
// loop until i-th Fibonacci number is
// less than or equal to N
int i = 2;
do {
dp[i] = dp[i - 1] + dp[i - 2];
} while (dp[i++] <= N);
// result is (i - 2) because i will be
// incremented one extra in while loop
// and we want the last value which is
// smaller than N, so one more decrement
return i - 2;
}
Also I am not clear what it means // result is (i - 2) because i will be incremented one extra in while loop and we want the last value which is smaller than N, so one more decrement return (i - 2);