- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum games played by winner in C++
Problem statement
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
Example
If There are 3 players then 2 games are required to decide the winner as follows −
Game – 1: player 1 vs player 2
Game - 2: player 2 vs winner from Game - 1
Algorithm
- 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] Which is same as the Fibonacci series relation, so our final answer will be the index of the maximal Fibonacci number which is less than or equal to given number of players in the input
Example
#include <bits/stdc++.h> using namespace std; int getMaxGamesToDecideWinner(int n) { int dp[n]; dp[0] = 1; dp[1] = 2; int idx = 2; do { dp[idx] = dp[idx - 1] + dp[idx - 2]; } while(dp[idx++] <= n); return (idx - 2); } int main() { int players = 3; cout << "Maximum games required to decide winner = " << getMaxGamesToDecideWinner(players) << endl; return 0; }
Output
When you compile and execute above program. It generates following output −
Maximum games required to decide winner = 2
Advertisements