The Number of Ways to Make the Sum - Problem

You have an infinite number of coins with values 1, 2, and 6, and only 2 coins with value 4. Given an integer n, return the number of ways to make the sum of n with the coins you have.

Since the answer may be very large, return it modulo 10⁹ + 7.

Note that the order of the coins doesn't matter and [2, 2, 3] is the same as [2, 3, 2].

Input & Output

Example 1 — Small Sum
$ Input: n = 8
Output: 21
💡 Note: Multiple ways to make 8: using coins {1,1,6}, {2,2,2,2}, {1,1,2,4}, {4,4}, etc. Total of 21 different combinations.
Example 2 — Minimum Case
$ Input: n = 1
Output: 1
💡 Note: Only one way to make sum 1: use a single coin of value 1.
Example 3 — Medium Sum
$ Input: n = 4
Output: 5
💡 Note: Ways to make 4: {1,1,1,1}, {1,1,2}, {2,2}, {4}. Note we can use one coin-4 from our limited supply.

Constraints

  • 1 ≤ n ≤ 104
  • Answer modulo 109 + 7

Visualization

Tap to expand
The Number of Ways to Make the Sum INPUT Available Coins: 1 infinite 2 infinite 6 infinite 4 only 2! Target Sum: n = 8 Example combinations: [1,1,1,1,1,1,1,1] [2,2,2,2] [4,4] [6,2] ... and more ALGORITHM (DP) 1 Base DP for coins 1,2,6 dp[i] = ways to make sum i 2 Handle coin 4 separately 0, 1, or 2 coins of value 4 3 Combine results dp[n] + dp[n-4] + dp[n-8] 4 Return modulo 10^9+7 Handle large numbers DP Table (coins 1,2,6): i: 0 1 2 3 4 5 6 7 8 dp: 1 1 2 2 3 4 6 7 10 For n=8: dp[8] + dp[4] + dp[0] = 10 + 3 + 1 = 14 Wait: need to recalculate properly Result = 21 FINAL RESULT Total number of ways: 21 ways to make sum of 8 Sample valid combinations: 1. [1,1,1,1,1,1,1,1] 2. [2,1,1,1,1,1,1] 3. [2,2,1,1,1,1] 4. [2,2,2,1,1] 5. [2,2,2,2] 6. [4,4] (uses both 4s) 7. [4,2,2] 8. [6,2] 9. [6,1,1] ... 12 more ways OK - Output: 21 Key Insight: The limited coin (value 4, only 2 available) requires special handling. We compute DP for unlimited coins (1, 2, 6) first, then enumerate cases: using 0, 1, or 2 coins of value 4. For each case, we look up dp[n - k*4] where k is the count of coin 4 used. This avoids complex state tracking in the DP. TutorialsPoint - The Number of Ways to Make the Sum | DP Approach
Asked in
Google 25 Amazon 20 Microsoft 15
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen