Maximizing Probability of one type from N containers in C++

C++Server Side ProgrammingProgramming

Probability Pi= (No. of Favourable Outcomes) / (Total no. of Outcomes).

Given is a number N which is the number of containers present. And we have N copies of two numbers X and Y. The task is to divide copies of one number X into N containers such that the probability of drawing a copy of X is maximum. From above it can be seen that to maximize Pi, we can either maximize the numerator ( No. of favourable outcomes) or minimize the denominator(Total no. of Outcomes). This can be done in a manner that only one container has a copy of Y and all containers have copies of X. N-1 containers have a copy of X each ( N-1 copies of X). And 1 container has 1 copy of Y and N copies of Y.

Probability (copy of X from first (n-1) containers) = Pn-1= 1

Probability (copy of X from last container) = Pn = 1/(n+1)

Pm = Pn-1 * (n – 1) + Pn
∴ Pm = n / (n + 1)

Input− N=1

Output− Maximum probability for N=1 is 0.5

Explanation − As there is only 1 container and 1 copy of X and Y each in it. Maximum probability of drawing X is 0.5.

Input− N=3

Output− Maximum probability for N=1 is 0.75

Explanation − Here All containers have 1 copy of X and the last one has all 3 copies of Y.

Approach used in the below program is as follows

  • Input an integer value for N that is the number of containers.

  • Declare a variable to store the maximum probability of X say maxP.

  • For given N calculate maxP as N/(N+1).


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   int N=3;
   double maxP = (double)N / (N + 1);
   cout << "Maximum Probability for N = " << N << " is, " <<maxP << endl;
   return 0;


If we run the above code it will generate the following output −

Maximum Probability for N = 3 is, 0.75
Published on 14-Aug-2020 07:39:41