
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Smallest and Largest Number of Children in Game Before Start
Suppose we have an array A with K number of elements. Consider, in a game there are N players and a game master is there. This game has K rounds. In ith round game master announces to form groups with A[i] number of children. Then the remaining children form as many groups of A[i] children as possible. One child cannot take part into multiple groups. Those who are left without a group leave the game. The others proceed to the next round. A round may have with no player loss. In the end, after the K-th round, there are exactly two children left, and they are declared the winners. We have to find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of N exist.
So, if the input is like A = [3, 4, 3, 2], then the output will be [6, 8], because if game starts with 6 children, then it proceeds
In round 1, 6 of them form two groups of 3 people
They are forming two groups with 4 and 2 children
Then a group with 1 child and another with 3, and that 1 will leave the game
Three of them form a group of 1 and 2. and 1 will leave.
last 2 children are declared the winners.
Steps
To solve this, we will follow these steps −
n := size of A Define a large array a, l, r, a of size: 100010. l := 2, r = 2 for initialize i := 1, when i <= n, update (increase i by 1), do: a[i] := A[i - 1] for initialize i := n, when i >= 1, update (decrease i by 1), do: x := a[i], L := (l + x - 1) if L > R, then: return -1, 0 l := L, r = R + x - 1 return l, r
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A){ int n = A.size(); int l, r, a[100010]; l = 2, r = 2; for (int i = 1; i <= n; i++) a[i] = A[i - 1]; for (int i = n; i >= 1; i--){ int x = a[i], L = (l + x - 1) / x * x, R = r / x * x; if (L > R){ cout << "-1, 0"; } l = L, r = R + x - 1; } cout << l << ", " << r << endl; return; } int main(){ vector<int> A = { 3, 4, 3, 2 }; solve(A); }
Input
{ 3, 4, 3, 2 }
Output
6, 8