Lv.2dp
Coin Change Ways
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given distinct coin denominations coins (unlimited supply of each) and an amount, return the number of ways to make exactly
amount, where the order of coins does not matter (1 + 2 and 2 + 1 are the same way). Return it modulo
; return 0 if it is impossible.
Examples
| coins | amount | result |
|---|---|---|
[1, 2, 5] | 5 | 4 |
[2] | 3 | 0 |
[3, 7] | 21 | 2 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(coins: int[], amount: int) → int
Constraints
-
coins.length, distinct values,coins[i] -
amount
Expected complexity
- Time
- O(C * A)
- Space
- O(A)
Examples
| coins | amount | Expected |
|---|---|---|
[1,2,5] | 5 | 4 |
[2] | 3 | 0 |
[3,7] | 21 | 2 |
Hint
Hint
ways[0] = 1; for each coin c (outer loop) and each amount a from c up, ways[a] += ways[a - c]. Looping over coins on
the outside is what stops 1+2 and 2+1 from being counted twice. Summing every possible count of each coin is for
small coins and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 4 | verdict only |