There are ‘p’ balls of type P, ‘q’ balls of type Q and ‘r’ balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.
Input : p = 1, q = 1, r = 0 Output : 2 There are only two arrangements PQ and QP Input : p = 1, q = 1, r = 1 Output : 6 There are only six arrangements PQR, QPR, QRP, RQP, PRQ and RPQ Input : p = 2, q = 1, r = 1 Output : 6 There are only six arrangements PQRP, QPRP, PRQP, RPQP, PRPQ and PQPR
We strongly recommend that you click here and practice it, before moving on to the solution.
The naive solution to this problem is a recursive solution. We recursively call for three cases
1) Last ball to be placed is of type P
2) Last ball to be placed is of type Q
3) Last ball to be placed is of type R
Below is the implementation of above idea.
Time Complexity of this solution is exponential.
We can observe that there are many subproblems being solved again and again so the problem can be solved using Dynamic Programming (DP). We can easily make memoization solution to this problem.
Time complexity : O(p*q*r)
Auxiliary Space : O(p*q*r*3)
This article is contributed by Bhavuk Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program to check if water tank overflows when n solid balls are dipped in the water tank
- Number of ways to arrange N items under given constraints
- Number of ways to arrange a word such that all vowels occur together
- Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
- Number of ways to form an array with distinct adjacent elements
- Permutations to arrange N persons around a circular table
- Maximum sum such that no two elements are adjacent
- Check whether given three numbers are adjacent primes
- Maximum sum of difference of adjacent elements
- Maximum sum in a 2 x n grid such that no two elements are adjacent
- C++ Data Types
- Count of strings where adjacent characters are of difference one
- Making zero array by decrementing pairs of adjacent
- Maximum sum in circular array such that no two elements are adjacent
- Count of arrays in which all adjacent elements are such that one of them divide the another