Skip to content

Instantly share code, notes, and snippets.

@jacoelho
Last active October 19, 2019 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacoelho/f4ec9923f75af440eb30ed6580b72549 to your computer and use it in GitHub Desktop.
Save jacoelho/f4ec9923f75af440eb30ed6580b72549 to your computer and use it in GitHub Desktop.
// coin change kata
fun largestCoin(coins: IntArray, amount: Int): Int? =
try {
coins.first { coin -> coin <= amount }
} catch (_: NoSuchElementException) {
null
}
fun coinChange(coins: IntArray, amount: Int): Int {
val coinsSorted = coins.sortedArrayDescending()
tailrec fun recur(count: Int = 0, amount: Int): Int {
return if (amount == 0) {
count
} else {
val coin = largestCoin(coinsSorted, amount) ?: return -1
recur(count + 1, amount - coin)
}
}
return recur(amount = amount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment