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.
- Ways of transforming one string to other by removing 0 or more characters
- Ways to write n as sum of two or more positive integers
- Find if string is K-Palindrome or not | Set 2
- Longest Common Increasing Subsequence (LCS + LIS)
- Wildcard Pattern Matching
- Find if string is K-Palindrome or not | Set 1
- Minimum time to finish tasks without skipping two consecutive
- Maximum profit by buying and selling a share at most k times
- A Space Optimized Solution of LCS
- Count number of ways to fill a "n x 4" grid using "1 x 4" tiles
- Weighted Job Scheduling in O(n Log n) time
- Count number of subsets having a particular XOR value
- Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique cap to every person)
- Shortest path with exactly k edges in a directed and weighted graph
- 0-1 Knapsack Problem | DP-10