Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*
- data class Context(val sum: Int, val coins: List<Int>)
- fun coins(amount: Int, coins: List<Int>): List<Int> {
- val sorted = coins.distinct().sortedDescending()
- val initialContext = Context(0, listOf())
- val queue = ArrayDeque<Context>()
- queue.offer(initialContext)
- while (queue.isNotEmpty()) {
- val context = queue.poll()
- if (context.sum == amount) {
- return context.coins
- }
- sorted.asSequence()
- .filter { context.coins.isEmpty() || it <= context.coins.last() }
- .filter { context.sum + it <= amount }
- .forEach { queue.offer(Context(context.sum + it, context.coins + it)) }
- }
- return listOf()
- }
- fun main() {
- val coins = coins(76, listOf(1, 3, 4, 10))
- println(coins)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement