kt: add «322. Coin Change»

URL:	https://leetcode.com/problems/coin-change/
This commit is contained in:
Matej Focko 2025-03-20 15:24:41 +01:00
parent a1d5ad7ba0
commit ba5a9515ba
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

29
kt/coin-change.kt Normal file
View file

@ -0,0 +1,29 @@
class Solution {
fun coinChange(
coins: IntArray,
amount: Int,
): Int =
IntArray(amount + 1) { Int.MAX_VALUE }.let { dp ->
// base case
dp[0] = 0
// sort the coins
coins.sort()
// precompute
(1..amount).forEach { total ->
for (coin in coins) {
when {
total - coin < 0 -> break
dp[total - coin] != Int.MAX_VALUE -> dp[total] = minOf(dp[total], 1 + dp[total - coin])
}
}
}
// return the minimum count for the target
when {
dp[amount] == Int.MAX_VALUE -> -1
else -> dp[amount]
}
}
}