Skip to content

Commit 3013089

Browse files
committed
Add Min Coin Combination
1 parent 85caad6 commit 3013089

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun minCoinCombinationBottomUp(coins: List<Int>, target: Int): Int {
2+
// The DP array will store the minimum number of coins needed for
3+
// each amount. Set each element to a large number initially.
4+
val dp = IntArray(target + 1) { Int.MAX_VALUE }
5+
// Base case: if the target is 0, then 0 coins are needed.
6+
dp[0] = 0
7+
// Update the DP array for all target amounts greater than 0.
8+
for (t in 1..target) {
9+
for (coin in coins) {
10+
if (coin <= t) {
11+
dp[t] = minOf(dp[t], 1 + dp[t - coin])
12+
}
13+
}
14+
}
15+
return if (dp[target] != Int.MAX_VALUE) dp[target] else -1
16+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
fun minCoinCombinationTopDown(coins: List<Int>, target: Int): Int {
2+
val memo = hashMapOf<Int, Int>()
3+
val result = topDownDp(coins, target, memo)
4+
return if (result == Int.MAX_VALUE) -1 else result
5+
}
6+
7+
fun topDownDp(coins: List<Int>, target: Int, memo: MutableMap<Int, Int>): Int {
8+
// Base case: if the target is 0, then 0 coins are needed to reach
9+
// it.
10+
if (target == 0) {
11+
return 0
12+
}
13+
if (target in memo) {
14+
return memo[target]!!
15+
}
16+
// Initialize 'minCoins' to a large number.
17+
var minCoins = Int.MAX_VALUE
18+
for (coin in coins) {
19+
// Avoid negative targets.
20+
if (coin <= target) {
21+
// Calculate the minimum number of coins needed if we use
22+
// the current coin.
23+
minCoins = minOf(minCoins, 1 + topDownDp(coins, target - coin, memo))
24+
}
25+
}
26+
memo[target] = minCoins
27+
return memo[target]!!
28+
}

0 commit comments

Comments
 (0)