kt: add «322. Coin Change»
URL: https://leetcode.com/problems/coin-change/
This commit is contained in:
parent
a1d5ad7ba0
commit
ba5a9515ba
1 changed files with 29 additions and 0 deletions
29
kt/coin-change.kt
Normal file
29
kt/coin-change.kt
Normal 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]
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue