Given three integers X, Y and Z, the task is to find the sum of all the numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times, under mod 10^9+7.
Input: X = 1, Y = 1, Z = 1 Output: 3675 Explanation: 4 + 5 + 6 + 45 + 54 + 56 + 65 + 46 + 64 + 456 + 465 + 546 + 564 + 645 + 654 = 3675 Input: X = 4, Y = 5, Z = 6 Output: 129422134
- As this problem has the property of sub-problems overlapping and optimal sub-structure, hence dynamic programming can be used to solve it.
- The numbers having exact i 4s, j 5s and k 6s for all i < x, j < y, j < z are required to get the required sum.
- Therefore the dp array exactnum[i][j][k] will store the exact count of numbers having exact i 4s, j 5s and k 6s.
- If exactnum[i – 1][j][k], exactnum[i][j – 1][k] and exactnum[i][j][k – 1] are already known, then it can be observed that the sum of these is the required answer, except in the case when exactnum[i – 1][j][k], exactnum[i][j – 1][k] or exactnum[i][j][k – 1] doesn’t exist. In that case, just skip it.
- exactsum[i][j][k] stores the sum of exact number having i 4's, j 5's and k 6's in the same way as
exactsum[i][j][k] = 10 * (exactsum[i - 1][j][k] + exactsum[i][j - 1][k] + exactsum[i][j][k - 1]) + 4 * exactnum[i - 1][j][k] + 5 * exactnum[i][j - 1][k] + 6 * exactnum[i][j][k - 1]
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.