The Number of Ways to Make the Sum - Problem

Imagine you're a cashier at a vintage arcade where coins have unusual denominations! You have access to:

  • Unlimited coins of values 1, 2, and 6
  • Only 2 coins of value 4

Given a target sum n, your task is to determine how many different ways you can make change to reach exactly that amount.

Important: The order of coins doesn't matter - using coins [2, 2, 6] is considered the same as [2, 6, 2].

Since the number of ways can be astronomically large, return your answer modulo 109 + 7.

Example: For n = 4, you could make it with: [4], [2, 2], [1, 1, 1, 1], [1, 1, 2] - that's 4 different ways!

Input & Output

example_1.py โ€” Basic case
$ Input: n = 4
โ€บ Output: 4
๐Ÿ’ก Note: Four ways to make sum 4: [4], [2,2], [1,1,1,1], [1,1,2]. The single 4-coin, two 2-coins, four 1-coins, or two 1-coins plus one 2-coin.
example_2.py โ€” Medium case
$ Input: n = 8
โ€บ Output: 12
๐Ÿ’ก Note: Multiple combinations possible including using 0, 1, or 2 of the 4-coins. Examples: [4,4], [6,2], [6,1,1], [2,2,2,2], [1,1,1,1,1,1,1,1], etc.
example_3.py โ€” Edge case
$ Input: n = 1
โ€บ Output: 1
๐Ÿ’ก Note: Only one way to make sum 1: using a single coin of value 1, since we cannot use fractional coins or combinations that exceed the target.

Visualization

Tap to expand
Coin Change: Mixed Constraints Strategyโˆžร—1โˆžร—2โˆžร—62ร—4Available CoinsStep 1: Standard DP for Unlimited Coinsdp[i] = ฮฃ dp[i-coin] for coin โˆˆ {1,2,6}Step 2: Add Limited Coin Contributionsโ€ข Use 0 coins of 4: dp[n]โ€ข Use 1 coin of 4: dp[n-4] (if n โ‰ฅ 4)โ€ข Use 2 coins of 4: dp[n-8] (if n โ‰ฅ 8)Final ResultTotal Ways = dp[n] + dp[n-4] + dp[n-8](Each term added only if the corresponding sum is valid)
Understanding the Visualization
1
Setup
Initialize DP array where dp[i] = ways to make sum i
2
Process Unlimited
Handle unlimited coins {1,2,6} using standard coin change DP
3
Add Limited
Add contributions from 1 or 2 uses of the limited 4-coin
4
Combine
Sum all valid ways: dp[n] + dp[n-4] + dp[n-8]
Key Takeaway
๐ŸŽฏ Key Insight: Separate unlimited coins (use standard DP) from limited coins (enumerate all valid usages). This decomposition makes complex constraint problems manageable.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the DP array for each coin type, total time is proportional to n times number of coin types

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

DP array of size n+1 to store the number of ways for each sum

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 104
  • You have unlimited coins of values 1, 2, and 6
  • You have exactly 2 coins of value 4
  • Return answer modulo 109 + 7
Asked in
Google 32 Amazon 28 Meta 19 Microsoft 15 Apple 12
38.4K Views
High Frequency
~18 min Avg. Time
1.2K 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