Problem Description
Given an integer n, determine the number of combinations to form the sum n using an infinite number of coins with values 1, 2, and 6, along with only 2 coins available with a value of 4. Note that the order in which the coins are selected does not create a distinct combination.
Key Insights
- The unlimited coins (1, 2, 6) allow the use of the classic coin change dynamic programming (DP) approach.
- The value 4 coin is limited (only 2 available), so we must consider separately the cases where 0, 1, or 2 coins of value 4 are used.
- For every option of using 0 to 2 coins of value 4, we compute the remaining sum to be formed using the unlimited coins.
- Sum the valid ways modulo 10^9+7.
Space and Time Complexity
Time Complexity: O(n) – We compute a DP array of size n for the unlimited coins. Space Complexity: O(n) – We use an additional DP array to store the number of ways for each amount up to n.
Solution
We first compute a DP array (dpInf) which counts the number of ways to form every sum from 0 to n using the infinite coins (1, 2, 6). This is done using the standard coin change approach: for each coin, iterate through all sums from the coin’s value up to n and update dpInf.
After filling dpInf, we consider the limited coin (4), which can be used 0, 1, or 2 times. For each possibility, subtract the total contribution of coin 4 (i.e. count4 * 4) from n, and add dpInf[remaining] to the result if the remaining sum is non-negative. Finally, we return the answer modulo 10^9+7.